• 445. 两数相加 II





    思路:

    先倒置,再求和,将结果倒置返回。

    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            # step1:先反转l1和l2
            link1 = None
            while l1:
                temp = l1.next
                l1.next = link1
                link1 = l1
                l1 = temp
            link2 = None
            while l2:
                temp = l2.next
                l2.next = link2
                link2 = l2
                l2 = temp
    
            # step2:两数相加
            pre = node = ListNode(0)
            # 进位
            extra = 0
            while link1 and link2:
                node.next = ListNode(0)
                # 求当前位的总和
                sum = link1.val + link2.val + extra
                # 计算当前位的值
                node.next.val = sum % 10
                # 计算进位
                extra = int(sum / 10)
                # 顺移
                node = node.next
                link1 = link1.next
                link2 = link2.next
    
            res = link1 or link2
            while res:
                node.next = ListNode(0)
                sum = res.val + extra
                node.next.val = sum % 10
                extra = int(sum / 10)
                node = node.next
                res = res.next
            if extra:
                node.next = ListNode(0)
                node.next.val = extra
    
            # step3:反转结果链表
            pre = pre.next
            ans = None
            while pre:
                temp = pre.next
                pre.next = ans
                ans = pre
                pre = temp
            return ans
    
  • 相关阅读:
    select下拉的value和option内值得获取
    express模块下GET和POST获取前台数据
    Node.js---fs模块
    Node.js---MySQL的增删改查
    Node.js--mysql的应用
    Node.js-router(将大服务拆分成一个个小服务)
    22
    窗口切换
    IO
    第一次实训作业
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12857278.html
Copyright © 2020-2023  润新知