小黑做法
# Definition for singly-linked list.# class ListNode:#def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution:def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:# 由链表获取数字def get_num(l):temp = 0i = 1while l:num = l.valtemp = num * i + tempi *= 10l = l.nextreturn tempn1 = get_num(l1)n2 = get_num(l2)head = ListNode()link = head# 数字加和后输出链表for c in str(n1+n2)[::-1]:c = int(c)link.next = ListNode(val = c)link = link.nextreturn head.next
模拟法
# Definition for singly-linked list.# class ListNode:#def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution:def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:head = ListNode()link = head# 进位carry = 0while l1 or l2:# 获取两个数字n1 = 0n2 = 0if l1:n1 = l1.vall1 = l1.nextif l2:n2 = l2.vall2 = l2.next# 加和操作sum_ = n1 + n2 + carry# 添加结点link.next = ListNode(val = sum_ % 10)link = link.next# 计算进位carry = sum_ // 10# 判断进位if carry:link.next = ListNode(val=1)return head.next
小黑生活记录
晚上冒雨跟学长吃了串串香,感觉最近接连出去吃身体都扛不住了,需要调节一下了,不能老出去吃了。
如果觉得《小黑夜晚冒雨加餐leetcode之旅:2. 两数相加》对你有帮助,请点赞、收藏,并留下你的观点哦!