Leetcode篇:两数之和

Posted 恩zzq我是

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode篇:两数之和相关的知识,希望对你有一定的参考价值。


@author: ZZQ
@software: PyCharm
@file: addTwoNumbers.py
@time: 2018/9/18 10:35
要求:给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
e.g.: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
------------------------------------------------------------------------------------------

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution():
    def __init__(self):
        pass

    def addsubtwonumber(self, *args):
        arg_len =len(*args)
        sum = 0
        for arg in range(arg_len):
            sum += args[0][arg]
        return sum % 10, sum / 10

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None and l2 is None:
            return None

        if l1 is None:
            return l2

        if l2 is None:
            return l1

        l3 = ListNode(0)
        head = l3
        temp = 0
        temp_rem = ListNode(temp)
        while l1 is not None and l2 is not None:
            s, rem = self.addsubtwonumber([l1.val, l2.val, temp_rem.val])
            l3.next = ListNode(s)
            temp_rem.val = rem
            l3 = l3.next
            l2 = l2.next
            l1 = l1.next
        temp = 0
        # temp_rem.val = temp
        if l1 is None and l2 is not None:
            while l2 is not None:
                s, rem = self.addsubtwonumber([l2.val, temp_rem.val])
                l3.next = ListNode(s)
                l3 = l3.next
                l2 = l2.next
                temp_rem.val = rem
        else:
            if l1 is not None and l2 is None:
                while l1 is not None:
                    s, rem = self.addsubtwonumber([l1.val, temp_rem.val])
                    l3.next = ListNode(s)
                    l3 = l3.next
                    l1 = l1.next
                    temp_rem.val = rem
        if temp_rem.val != 0:
            l3.next = ListNode(temp_rem.val)
        return head.next


if __name__ == "__main__":
    answer = Solution()
    l1 = ListNode(9)
    l1.next = ListNode(8)
    l2 = ListNode(1)
    l3 = answer.addTwoNumbers(l1, l2)
    while l3 is not None:
        print l3.val
        l3 = l3.next









以上是关于Leetcode篇:两数之和的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 1. 两数之和(带图)

1. 两数之和---双指针篇七

LeetCode:两数之和

LeetCode 1两数之和

LeetCode——1.两数之和

C#leetcode练习简单篇