LeetCode 2. 两数相加

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

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

# 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
        """
        num1 = 0
        num2 = 0
        i = 0
        while True:
            if l1 == None:
                break
            num1 += l1.val * (10 ** i)
            i += 1
            l1 = l1.next

        i = 0
        while True:
            if l2 == None:
                break
            num2 += l2.val * (10 ** i)
            i += 1
            l2 = l2.next

        result = num1 + num2
        if result == 0:
            return ListNode(0)

        li = []
        while result > 0:
            node = ListNode(None)
            node.val = result % 10
            node.next = None
            result /= 10
            li.append(node)

        for i in range(len(li) - 1):
            li[i].next = li[i+1]

        return li[0]

你可能感兴趣的:(#,LeetCode)