Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode-2. Add Two Numbers #6

Closed
ninehills opened this issue Jul 13, 2017 · 0 comments
Closed

LeetCode-2. Add Two Numbers #6

ninehills opened this issue Jul 13, 2017 · 0 comments
Labels

Comments

@ninehills
Copy link
Owner

ninehills commented Jul 13, 2017

20170714

题目

https://leetcode.com/problems/add-two-numbers/

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

注意点:列表给的就是反序的,是342+465 = 807

思路

  • 链表遍历,另外进位只可能进1,不可能进更多的数
  • 注意增加了一个RootNode,用它的next放第一个节点
  • 需要添加辅助的函数和类定义用来测试和debug

解答

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
        
    def __str__(self):
        return "Node({0}->[{1}])".format(self.val, self.next)

           
def init_list(l):
    before = None
    for i in l[::-1]:
        n = ListNode(i)
        n.next = before
        before = n
    return n

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0
        root = before = ListNode(None)
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            z = v1 + v2 + carry
            if z >= 10:
                x = z - 10
                carry = 1
            else:
                x = z
                carry = 0
            node = ListNode(x)
            before.next = node
            before = node
        return root.next

# [7,0,8]
print Solution().addTwoNumbers(init_list([2,4,3]), init_list([5,6,4]))
@ninehills ninehills changed the title LeetCode2. Add Two Numbers LeetCode-2. Add Two Numbers Jul 13, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant