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 -> 8
Explanation: 342 + 465 = 807.
Solution
Approach 1: Elementary Math
这里用链表结点相加计算,将l1,l2的和加到l1中。
1. 考虑链表长度:l1 < l2:将l1的尾指针指向l2 -- 将来并入l1
l1 >= l2: 继续在l1运算
2. 考虑最后一位进位:加入新的进位结点。
由于p1最后一定指向None而不能指向进位结点,故用tail指针标记每次的尾结点,
tail.next = ListNode(carry)使得l1与进位结点相连接。
1 class Solution: 2 def addTwoNumbers(self, l1, l2): 3 """ 4 :type l1: ListNode 5 :type l2: ListNode 6 :rtype: ListNode 7 """ 8 p1, p2 = l1, l2 9 carry = 0 10 tail = p1 11 while p1 is not None and p2 is not None: 12 cnt = p1.val + p2. val + carry 13 p1.val = cnt % 10 14 carry = cnt // 10 15 tail = p1 16 p1 = p1.next 17 p2 = p2.next 18 19 if p2 is not None: 20 tail.next = p2 21 tail = tail.next 22 p1 = tail 23 24 while p1 is not None: 25 cnt = p1.val + carry 26 print(carry, p1) 27 p1.val = cnt % 10 28 carry = cnt // 10 29 tail = p1 30 p1 = p1.next 31 32 if carry > 0: 33 tail.next = ListNode(carry) 34 tail = tail.next 35 tail.next = None 36 return l1
Beats: 95.42%
Runtime: 108ms
Approach 2. Turn into Integers
这个解法也许不是出题人希望的正规解法:
先将linked list表示的数,用整数表示,
然后整数相加,将所得和,用%/分解,表示成linked list形式。
Notice:
这里注意,所得和为0的情况不要忽略,要单独讨论。
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def addTwoNumbers(self, l1, l2): 9 """ 10 :type l1: ListNode 11 :type l2: ListNode 12 :rtype: ListNode 13 """ 14 def getInteger(l): 15 res = 0 16 cnt = 1 17 while l is not None: 18 res = res + l.val * cnt 19 cnt *= 10 20 l = l.next 21 return res 22 sum_integer = getInteger(l1) + getInteger(l2) 23 if sum_integer == 0: 24 return ListNode(0) 25 26 head = ListNode(0) 27 l = head 28 while sum_integer > 0: 29 l.next = ListNode(sum_integer % 10) 30 l = l.next 31 sum_integer /= 10 32 return head.next
Beats: 94.47%
Runtime: 68ms