Wednesday, October 17, 2012

[LeetCode] Add Two Numbers

Question:

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

解题思路: 一道实现题




public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
           ListNode p1 = l1;
           ListNode p2 = l2;
           ListNode head = new ListNode(0);
           ListNode p = head;
           
           int add = 0;
           
           while(p1 != null || p2 != null || add > 0){
               int add1 = 0, add2 = 0;
               
               if(p1 != null){
                  add1 = p1.val;
                  p1 = p1.next;
               } 
               
               if(p2 != null){
                   add2 = p2.val;
                   p2 = p2.next;
               } 
               
                int val = (add1 + add2 + add)%10;
                add = (add1 + add2 + add)/10;
                
                ListNode l = new ListNode(val);
                p.next = l;
                p = p.next;
           }
           
           return head.next;
    }

No comments:

Post a Comment