Leetcode #2 Add Two Numbers
题目描述
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.
题解:
知识点:
1. 链表
2. 进位
1.链表
以 Leetcode 所给定义为例
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
__init__介绍
python class 里的函数:代表定义class时创建的变量
self: class 本身
x: 在创建时需要输入的变量
这个class定义了两个变量: val 和 next
next:指向下一个节点
val:本节点的值
example:
N = ListNode(3)
N 为新节点, x = 3 并赋值给val
现在 N.val = 3
N.next = None
2.进位
定义 carry为进位项
AC代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
r = ListNode(0) #创建储存答案的链表的始节点
nowNode = r #定义当前储存答案的节点
carry = 0 # 上一次残留的进位
while l1 or l2:#两个链表至少一个不是空
x = l1.val if l1 else 0 #不空就赋值,否则为0
y = l2.val if l2 else 0
result = x + y + carry # 相加
carry = result // 10 #除以10的商->进位
nowNode.next = ListNode(result%10) # 下一个节点的值是和的个位数,使当前节点指向下一节点
nowNode = nowNode.next #到下一节点
if l1: l1 = l1.next #不为空则后移到下一节点
if l2: l2 = l2.next
#循环后多进位 再创建一个节点
if carry ==1:
nowNode.next = ListNode(1)
return r.next