问题描述:
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
注意一下有些特殊的测试用例:Input: [1], [9,9] Input: [1,8], [0] Input: [5], [5] Input: [0], [0]
1 public class Solution { 2 3 public ListNode addTwoNumbers(ListNode x, ListNode y) { 4 int temp = 0; 5 int pre = 0; 6 int carry = 0; 7 ListNode top = new ListNode(0); 8 ListNode sum = top; 9 while (x != null || y != null || carry != 0) { 10 if (x != null) { 11 temp += x.val; 12 x = x.next; 13 } 14 if (y != null) { 15 temp += y.val; 16 y = y.next; 17 } 18 19 temp += carry; 20 21 if (temp >= 10) { 22 carry = 1; 23 pre = temp % 10; 24 temp = 0; 25 } else { 26 carry = 0; 27 pre = temp; 28 temp = 0; 29 } 30 sum.val = pre; 31 if (carry != 0 || x != null || y != null) { 32 sum.next = new ListNode(0); 33 sum = sum.next; 34 } 35 } 36 return top; 37 } 38 }
注意一下进位,边界。跑了412 ms
原文:http://www.cnblogs.com/AloneAli/p/4567705.html