zoukankan      html  css  js  c++  java
  • 两数之和

    题目描述:

    给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
    你可以假设除了数字 0 之外,这两个数字都不会以零开头。

    示例:

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807
    

    考虑情况

    测试用例 说明
    l1=[0,1], l2=[0,1,2] 当一个列表比另一个列表长时。
    l1=[] , l2=[0,1] 当一个列表为空时,即出现空列表。
    l1=[9,9] , l2=[1] 求和运算最后可能出现额外的进位,这一点很容易被遗忘

    因为9+9 +1 位19 不可能进位是2 所以:

    # Definition for singly-linked list.
    class ListNode:
         def __init__(self, x):
             self.val = x
             self.next = None
    
    class Solution:
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
           if l1 is None:
               return l2
           if l2 is None:
              return l1
          tmp = ListNode(0)
          res = tmp
          flag = 0
          while l1 or l2:
              tmpsum = 0
              if l1:
                tmpsum = l1.val 
                l1 = l1.next # 为下一次的取和做准备
              if l2:
                tmpsum += l2.val
                l2 = l2.next
             tmpnum = ((tmpsum + flag) % 10) # 取个位值
             flag = ((tmpsum + flag) // 10 ) # 看是否进位
             res.next = ListNode(tmpnum)
             res = res.next
             if flag:
                res.next = ListNode(1)
          res = tmp.next
          del tmp
          return res
    
  • 相关阅读:
    背水一战 Windows 10 (90)
    背水一战 Windows 10 (89)
    背水一战 Windows 10 (88)
    背水一战 Windows 10 (87)
    背水一战 Windows 10 (86)
    背水一战 Windows 10 (85)
    背水一战 Windows 10 (84)
    背水一战 Windows 10 (83)
    背水一战 Windows 10 (82)
    背水一战 Windows 10 (81)
  • 原文地址:https://www.cnblogs.com/Stay-J/p/9929068.html
Copyright © 2011-2022 走看看