快速索引
【2】Add two numbers
Problen describtion
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.
Problem explain
实际上是一个加法竖式的问题。
图参考来源:[https://leetcode.com/problems/add-two-numbers/discuss/352181/Python3-60-ms-faster-than-99.92-.-Update-Carry-sum10]
carry为进位,cur为当前位结果,考虑到产生的进位问题,计算cur需要使用取模运算,cur记录余数,carry记录进位。(实际上,carry取值非0即1)
没有什么难点,借鉴一个思路,处理两个整数相加可以用链表进行存储,从低位向高位进行计算。推广到浮点数:小数点左边从低位向高位存储,小数点右边从高位向低位存储(即以小数点为起点向两边扩展),计算顺序同样如此。
在计算式可能出现L1和L2的位数不相符的情况,因为我们是从低位向高位存储的,每运算一位再将指针向后移动,所以在进行加法操作的时候对L1和L2分开处理,先加L1再加L2,两块相互独立,不能放在一个判定条件下。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur =ListNode(0)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
cur.next = ListNode(carry%10)
cur = cur.next
carry //=10
return dummy.next