Wednesday, May 3, 2017

LeetCode 2nd time 2. Add Two Numbers LeetCode Java

 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {  
     if(l1==null) return l2;  
     if(l2==null) return l1;  
     int sum=l1.val+l2.val;  
     int carry=sum/10;  
     ListNode head=new ListNode(sum%10);  
     ListNode currentNode=head;  
     l1=l1.next;  
     l2=l2.next;  
     while(l1!=null || l2!=null || carry!=0){  
      int val1=(l1==null)? 0:l1.val;  
      int val2=(l2==null)? 0:l2.val;  
      sum=val1+val2+carry;  
      carry=sum/10;  
      ListNode nextNode=new ListNode(sum%10);  
      currentNode.next=nextNode;  
      currentNode=nextNode;  
     if(l1!=null) l1=l1.next;  
     if(l2!=null) l2=l2.next;  
     }  
     return head;  
   }  

No comments:

Post a Comment