Add Two Numbers

来源:互联网 发布:.net cms 编辑:程序博客网 时间:2024/06/05 16:03

思路不难,但是要考虑各种边界情况,尤其是有个大坑如果用int会溢出,换成long就没事了。

Java版:

public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        //必须用long        long n1 = 0;        long n2 = 0;        int index = 0;        while(l1 != null){            n1 = n1 + (l1.val)*((long)Math.pow(10, index));            index++;            l1 = l1.next;        }        index = 0;        while(l2 != null){            n2 = n2 + (l2.val)*((long)Math.pow(10, index));            index++;            l2 = l2.next;        }        long sum = n1 + n2;        long t = sum;        if(t == 0){            return new ListNode(0);        }        LinkedList<Long> list = new LinkedList<Long>();        while(t != 0){            list.add(t%10);            t = t/10;        }        ListNode n = null;        ListNode pre = null;        while(!list.isEmpty()){            int h = (int)list.getLast().longValue();            list.removeLast();            n = new ListNode(h);            n.next = pre;            pre = n;        }        return n;    }}


0 0
原创粉丝点击