2.Add two numbers

2018-02-11  本文已影响0人  CelloRen

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode help=new ListNode(0);
        ListNode stay=help;
        int carry=0;
        if(l1==null && l2==null) return null;
        while(l1!=null || l2!=null || carry!=0){
            ListNode temp = new ListNode(0);
            int sum = ((l1==null)?0:l1.val)+((l2==null)?0:l2.val)+carry;
            temp.val=sum%10;
            help.next=temp;
            carry=sum/10;
            help=temp;
            if(l1!=null) l1=l1.next;
            if(l2!=null) l2=l2.next;
        }
        return stay.next;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读