zoukankan      html  css  js  c++  java
  • 两数相加

    思路:因为数是用链表逆序表示的,因此先用列表将这些数提取出来。然后每一位对应相加大于10就进位,进位用carry表示。有两个特殊情况要考虑:(1)象5+5这种,两个数的位数一样,最后要增加一位。(2)象1+99这种,两个数的位数不一样,先将1+9相加跳出循环,后面是carry+9=10,又出现了一个进位。

    # 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
            """
            stack1 = []
            stack2 = []
            while l1:
                stack1.append(l1.val)
                l1 = l1.next
            while l2:
                stack2.append(l2.val)
                l2 = l2.next
            if len(stack1) > len(stack2):
                stack1, stack2 = stack2, stack1
            carry = 0
            head = ListNode(-1)
            p = head
            while stack1:
                tmp = stack1.pop(0) + stack2.pop(0) + carry
                carry = tmp // 10
                node = ListNode(tmp%10)
                p.next = node
                p = p.next
            if not stack2 and carry == 1:
                node = ListNode(1)
                p.next = node 
                p = p.next
                carry = 0
            elif stack2:
                while stack2:
                    tmp = stack2.pop(0) + carry
                    carry = tmp // 10
                    node = ListNode(tmp%10)
                    p.next = node
                    p = p.next
                if carry == 1:
                    node = ListNode(1)
                    p.next = node 
                    p = p.next
            return head.next
    
  • 相关阅读:
    Python有哪些华而不实的技巧?
    json:dumps/loads & pickl
    json模块与第三方模块的引入
    os 及 sys 模块补充
    如何白嫖视频会员
    python和SAS的思考
    5、根据进程号PID查询其服务路径
    5、安装mongodb 异常
    2、shell 判断字符串是否包含另一个字符串
    【九校2D2T1】旋转子段
  • 原文地址:https://www.cnblogs.com/dolisun/p/11512939.html
Copyright © 2011-2022 走看看