Search This Blog

Thursday, December 27, 2012

LeetCode:Add Two Numbers

Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int carry =0;
        ListNode res = new ListNode(0);
        ListNode cur1 = l1, cur2 = l2, head=res;
        while(cur1!=null || cur2!=null){
            if(cur1!=null){
                carry+=cur1.val;
                cur1=cur1.next;
            }
            if(cur2!=null){
                carry+=cur2.val;
                cur2=cur2.next;
            }
            head.next=new ListNode(carry%10);
            head=head.next;
            carry/=10;
        }
        if(carry==1) head.next=new ListNode(1);
        return res.next;
    }
}

1 comment:

Anonymous said...

This solution is wrong. you did not take into account of two lists when they are of different length, say,

9-9-9
1