在 Python 中,有多种解法可以实现两数相加。以下是几种常见的解法:
- 逐位相加:将两个数的每一位进行相加,并考虑进位。使用循环遍历两个数的每一位,将对应位相加并考虑进位,然后将结果添加到一个新的列表中。最后,将列表转换为整数即可得到最终结果。
def addTwoNumbers(l1, l2):
carry = 0
head = ListNode(0)
curr = head
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = carry + x + y
carry = sum // 10
curr.next = ListNode(sum % 10)
curr = curr.next
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry > 0:
curr.next = ListNode(carry)
return head.next
- 递归相加:可以使用递归的方式实现两数相加。递归地处理每一位的相加,并将进位传递到下一位的相加中。
def addTwoNumbers(l1, l2, carry=0):
if not l1 and not l2 and not carry:
return None
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = carry + x + y
carry = sum // 10
result = ListNode(sum % 10)
l1_next = l1.next if l1 else None
l2_next = l2.next if l2 else None
result.next = addTwoNumbers(l1_next, l2_next, carry)
return result
- 倒序相加:如果两个数的位数不一致,可以在相加之前先将两个数补齐为相同长度。然后从最低位开始逐位相加,并考虑进位。
def addTwoNumbers(l1, l2):
len1 = get_length(l1)
len2 = get_length(l2)
if len1 > len2:
l2 = pad_zeros(l2, len1 - len2)
else:
l1 = pad_zeros(l1, len2 - len1)
head = ListNode(0)
curr = head
carry = 0
while l1 and l2:
sum = l1.val + l2.val + carry
carry = sum // 10
curr.next = ListNode(sum % 10)
curr = curr.next
l1 = l1.next
l2 = l2.next
if carry > 0:
curr.next = ListNode(carry)
return head.next
def get_length(node):
length = 0
while node:
length += 1
node = node.next
return length
def pad_zeros(node, num_zeros):
for _ in range(num_zeros):
new_node = ListNode(0)
new_node.next = node
node = new_node
return node
这些都是两数相加的常见解法,在实际应用中可以根据具体需求选择合适的方法。