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 contains 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

 

解答:

 1 public ListNode  addTwoNumbers(ListNode l1, ListNode l2) {
 2     ListNode dummyHead = new ListNode(0);
 3     ListNode p = l1;
 4     ListNode q = l2;
 5     ListNode curr = dummyHead;
 6 
 7     int carry = 0;
 8 
 9     while(p != null || q != null) {
10         int x = (p != null)?p.val:0;
11         int y = (q != null)?q.val:0;
12 
13         int digit = x + y + carry;
14         carry = digit / 10;
15         curr.next = new ListNode(digit % 10);
16         curr = curr.next;
17 
18         if(p != null) {
19             p = p.next;
20         }
21 
22         if(q != null) {
23             q = q.next;
24         }
25     }
26 
27     if(carry > 0) {
28         curr.next = new ListNode(carry);
29     }
30 
31     return dummyHead;
32 }

 

posted @ 2019-02-21 14:52  林木声  阅读(114)  评论(0编辑  收藏  举报