0002 - Add Two Number
Python Leetcode 问题: 0002 - Add Two Number
题目
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
传入 数字列表
及 最后答案加总数值
,回传 最后答案加总数值
是 数字列表
的第几个跟第几个数字的加总
答案
from typing import List
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
@staticmethod
# ListNode 转换成数字清单
def listNodeToNumList(HeadListNode: ListNode) -> List[int]:
# 数字清单
num_list = []
while HeadListNode is not None:
num_list.append(HeadListNode.val)
HeadListNode = HeadListNode.next
return num_list
@staticmethod
# 数字清单转换成 ListNode
def numListToListNode(nums_list: List[int]) -> ListNode:
# 初始化链结节点
HeadListNode = ListNode(None)
# 设定目前链结节点
CurrentListNode = HeadListNode
for value in nums_list:
# 设定链结节点的下一节点
CurrentListNode.next = ListNode(value)
# 将下一节点设为目前节点
CurrentListNode = CurrentListNode.next
return HeadListNode.next
def addTwoNumbers(self, FirstNumberListNode: ListNode, SecondNumberListNode: ListNode) -> ListNode:
# 建立答案节点,预设个位数是 0
AnswerListNode = ListNode(0)
CurrentAnswerListNode = AnswerListNode # 目前答案节点
number_1: int = 0 # 第 1 个加总数值
number_2: int = 0 # 第 2 个加总数值
carry_number: int = 0 # 加总后的进位数值
number_sum: int = 0 # 加总数值
while FirstNumberListNode is not None or SecondNumberListNode is not None or carry_number != 0:
# === 计算第 1 个数字 ===
if FirstNumberListNode is None:
# 若「第 1 数字节点」为 nil,表示没有数字可以做加总了,设定可加总数字为 0
number_1 = 0
else:
# 若「第 1 数字节点」有值,将节点数值设定为此次第 1 个加总数值
number_1 = FirstNumberListNode.val
FirstNumberListNode = FirstNumberListNode.next
# === 计算第 2 个数字 ===
if SecondNumberListNode is None:
# 若「第 2 数字节点」为 nil,表示没有数字可以做加总了,设定可加总数字为 0
number_2 = 0
else:
number_2 = SecondNumberListNode.val
SecondNumberListNode = SecondNumberListNode.next
# 加总数值
number_sum = number_1 + number_2 + carry_number
# 设定馀数为目前答案节点数值
CurrentAnswerListNode.next = ListNode(number_sum % 10)
# 设定答案节点的下一节点为目前节点,继续往后做加总
CurrentAnswerListNode = CurrentAnswerListNode.next
# 取得加总后的进位数值,继续往后做加总
carry_number = int(number_sum / 10)
return AnswerListNode.next
if __name__ == '__main__':
# begin
s = Solution()
print(s.listNodeToNumList(s.addTwoNumbers(s.numListToListNode([2, 4, 3]), s.numListToListNode([5, 6, 4]))))
print(s.listNodeToNumList(
s.addTwoNumbers(s.numListToListNode([9, 9, 9, 9, 9, 9, 9]), s.numListToListNode([9, 9, 9, 9]))))