标签:ret sum exce new its title nod ase res
题目:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
链接:https://leetcode.com/problems/add-two-numbers/#/description
4/3/2017
51ms, 88%
1 public class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 int carry = 0; 4 ListNode ret = new ListNode(-1); 5 ListNode dummy = ret; 6 int sum = 0; 7 8 while(l1 != null || l2 != null) { 9 if (l1 != null && l2 != null) { 10 sum = (l1.val + l2.val + carry) % 10; 11 carry = (l1.val + l2.val + carry) / 10; 12 l1 = l1.next; 13 l2 = l2.next; 14 } else if (l1 != null) { 15 sum = (l1.val + carry) % 10; 16 carry = (l1.val + carry) / 10; 17 l1 = l1.next; 18 } else { 19 sum = (l2.val + carry) % 10; 20 carry = (l2.val + carry) / 10; 21 l2 = l2.next; 22 } 23 ret.next = new ListNode(sum); 24 ret = ret.next; 25 } 26 if (carry == 1) { 27 ret.next = new ListNode(carry); 28 } 29 return dummy.next; 30 } 31 }
超时,难道就因为test case里有长度相差很大的2个list吗?但是看起来跟答案一样啊
1 public class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 int carry = 0; 4 ListNode ret = new ListNode(-1); 5 ListNode dummy = ret; 6 int value; 7 8 while(l1 != null || l2 != null) { 9 value = carry; 10 if (l1 != null) { 11 value += l1.val; 12 l1 = l1.next; 13 } 14 if (l1 != null) { 15 value += l2.val; 16 l2 = l2.next; 17 } 18 carry = value / 10; 19 ret.next = new ListNode(value % 10); 20 ret = ret.next; 21 } 22 if (carry == 1) { 23 ret.next = new ListNode(carry); 24 } 25 return dummy.next; 26 } 27 }
解答:https://leetcode.com/articles/add-two-numbers/
标签:ret sum exce new its title nod ase res
原文地址:http://www.cnblogs.com/panini/p/6664245.html