==============================================================================
【id】#2
【title】Add Two Numbers
【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.
【idea】
- 根据加法规则,从最低位开始相加,满十进一;初始化一个进位carry,逐位累加并得出每一步的进位和加和,初始化两个链表,记录最后的结果。
【code】
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0 #进位符
root = res = ListNode(0)
while l1 != None or l2 != None or carry != 0:
if l1 != None:
carry += l1.val
l1 = l1.next
if l2 != None:
carry += l2.val
l2 = l2.next
val = carry %10
carry /= 10
res.next = ListNode(val)
res = res.next
return root.next
【idea】
- 先得出两个因数再求和,这样不需要考虑进位问题。得出最后的结果后,处理炒成反转的列表,然后建两个链表输出。
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
val1 = val2 = 0
# res = ListNode(0)
i = j =0
while l1 :
val1 += (10**i)*(int(l1.val))
l1 = l1.next
i += 1
while l2:
val2 += (10**j)*(int(l2.val))
l2 = l2.next
j += 1
tmp = val1 + val2
tmp = list(str(tmp))
output = ListNode(tmp[::-1][0])
res = output
for x in tmp[::-1][1:]:
res.next = ListNode(int(x))
res = res.next
return output