1. 题目
2. 解析
字符串相加,采用末尾相加,直到加到两个数的第一位,最后需要判断商是否大于0。使用双指针解法
3. 核心代码
class Solution(object):
def add(self, a, b):
al = len(a) - 1
bl = len(b) - 1
sha = 0
result = ''
while al >= 0 or bl >= 0:
if al >= 0:
i = int(a[al])
else:
i = 0
if bl >= 0:
j = int(b[bl])
else:
j = 0
num = i + j + sha
y = num % 10
sha = num // 10
result += str(y)
al -= 1
bl -= 1
if sha != 0:
result += str(sha)
return result[::-1]
if __name__ == '__main__':
s = Solution()
print(s.add('9', '1'))
4. 题目变形
5. 解析
单链表的加法,利用双指针的形式进行每个位数的遍历,位数需要一一对应相加,链表尝尝需要使用一个0开始的头最后返回result.next作为结果
6. 核心代码
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
from typing import Optional
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
result = cur = ListNode()
sha = 0
while l1 or l2:
i = l1.val if l1 else 0
j = l2.val if l2 else 0
num = i + j + sha
sha = num // 10
r = num % 10
cur.next = ListNode(r)
if l1: l1 = l1.next
if l2: l2 = l2.next
cur = cur.next
if sha: cur.next = ListNode(sha)
return result.next
if __name__ == '__main__':
s = Solution()
x = ListNode(9, ListNode(9, ListNode(9, ListNode(9))))
y = ListNode(9, ListNode(9, ListNode(9)))
xx = s.addTwoNumbers(x, y)
while xx:
print(xx.val)
xx = xx.next
print(9999 + 999)