题目描述 原题
Description :
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8Explanation: 342 + 465 = 807.
原题翻译
描述:
给定两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。将两个数字相加并将其作为链表返回。
可以认为这两个数字不包含任何前导0,除了数字0本身。
例如:
输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)输出: 7 -> 0 -> 8解释: 342 + 465 = 807.
解法一(mine) 主要思想 将两个数字表示出来,相加,再转化成结果链表(考虑到两数和可能超过了int的限制,选择BigInteger)。 想法很简单,然而…Memory Limit Exceeded(内存超过限制)
未通过
源码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 public class Solution { public ListNode addTwoNumbers (ListNode l1, ListNode l2) { ListNode ln1 = l1, ln2 = l2; BigInteger a, b, temp1, temp2, b10; b10 = new BigInteger("10" ); temp1 = temp2 = new BigInteger("1" ); a = b = new BigInteger("0" ); while (ln1 != null ) { a = a.add(new BigInteger(ln1.val + "" ).multiply(temp1)); ln1 = ln1.next; temp1 = temp1.multiply(b10); } while (ln2 != null ) { b = b.add(new BigInteger(ln2.val + "" ).multiply(temp2)); ln2 = ln2.next; temp2 = temp2.multiply(b10); } BigInteger result = a.add(b); ListNode res; ListNode t = new ListNode(result.mod(b10).intValue()); result = result.divide(b10); res = t; while (result != new BigInteger("0" )) { t.next = new ListNode(result.mod(b10).intValue()); t = t.next; result = result.divide(b10); } return res; } }
解法二 主要思想 同时遍历两链表,将对应位上对两数相加(超过10的部分除以10再存起来,下一位继续用)
运行速度:超过了79.73%的解答。
内存使用:超过了90.28%的解答。
源码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Solution { public ListNode addTwoNumbers (ListNode l1, ListNode l2) { ListNode ln1 = l1, ln2 = l2, head = null , node = null ; int carry = 0 , remainder = 0 , sum = 0 ; head = node = new ListNode(-1 ); while (ln1 != null || ln2 != null || carry != 0 ) { sum = (ln1 != null ? ln1.val : 0 ) + (ln2 != null ? ln2.val : 0 ) + carry; carry = sum / 10 ; remainder = sum % 10 ; node = node.next = new ListNode(remainder); ln1 = (ln1 != null ? ln1.next : null ); ln2 = (ln2 != null ? ln2.next : null ); } return head.next; } }
解法三
第一名答案
主要思想 与解法二的思想类似。
运行速度:超过了100%的解答。
内存使用:超过了86.83%的解答。
源码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Solution { public ListNode addTwoNumbers (ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0 ), p1 = l1, p2 = l2, p = dummyHead; int carry = 0 ; while (p1 != null || p2 != null || carry != 0 ) { int digit = 0 + carry; if (p1 != null ) { digit += p1.val; p1 = p1.next; } if (p2 != null ) { digit += p2.val; p2 = p2.next; } carry = digit / 10 ; p.next = new ListNode(digit % 10 ); p = p.next; } return dummyHead.next; } }