2015年9月15日星期二

Leetcode 2 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
Solution 1: Can use two pointers. i and j travel on 1st list and 2nd list respectively, add them up and the carry over number to a new node in result list. The tricky part is that, the length of two lists may not be equal. When both i and j reach to the end, if carry over number is not 0, we still need to create the last new node.

 public class Solution {  
   public ListNode addTwoNumbers(ListNode l1, ListNode l2) {  
     ListNode dummy=new ListNode(0);  
     ListNode i=l1, j=l2, k=dummy;  
     int t=0;  
     while (i!=null || j!=null || t!=0) {  
       int sum=t;  
       if (i!=null) {  
         sum+=i.val;  
         i=i.next;  
       }  
       if (j!=null) {  
         sum+=j.val;  
         j=j.next;  
       }  
       k.next=new ListNode(sum%10);  
       k=k.next;  
       t=sum/10;  
     }  
     return dummy.next;  
   }  
 }  

没有评论:

发表评论