Saturday, November 14, 2015

[leetcode] Add two numbers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode r1, ListNode r2) {
        ListNode dummy = new ListNode(-1);
        ListNode previous = dummy;
        int carry = 0;
        while(r1 != null && r2 != null){
            previous.next = new ListNode((r1.val+r2.val+carry)%10);
            carry = (r1.val+r2.val+carry)/10;
            previous = previous.next;
            r1 = r1.next;
            r2 = r2.next;
        }
        ListNode leftOver = null;
        if (r1 != null) leftOver = r1;
        else if (r2 != null) leftOver = r2;
        while (leftOver != null){
            previous.next = new ListNode((leftOver.val+carry)%10);
            carry = (leftOver.val+carry) /10;
            previous = previous.next;
            leftOver = leftOver.next;
        }
        
        if (carry != 0){
            previous.next = new ListNode(carry);
        }
        return dummy.next;
    }
}

No comments:

Post a Comment