2017年7月13日 星期四

LeetCode題解 - 2. Add Two Numbers [Medium]

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

1. Code:
# 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
        """        
        rtype = None
        prev = None
        plugs = 0

        while (l1 is not None) or (l2 is not None) or plugs != 0:
            v1 = self._getListNodeValue(l1)
            v2 = self._getListNodeValue(l2)
            l1 = self._getNextListNode(l1)
            l2 = self._getNextListNode(l2)
            
            count = v1 + v2 + plugs
            plugs = count / 10
            
            ln = ListNode(count % 10)
            if rtype is None:
                rtype = ln
                prev = rtype
            else:
                prev.next = ln
                prev = prev.next
        
        return rtype
    
    def _getListNodeValue(self, ln):
        """
        :type l1: ListNode
        :rtype: number
        """        
        if not isinstance(ln, ListNode):
            return 0
        return ln.val
    
    def _getNextListNode(self, ln):
        """
        :type l1: ListNode
        :rtype: ListNode
        """        
        if not isinstance(ln, ListNode):
            return None
        return ln.next

心得:
一看見題目就覺得簡單啊,刷刷地就寫完了
點Run Code按鈕,嗯?怎麼會出現這種錯誤訊息
重新看一次題目,原來有定義一個class ListNode
我還以為會傳進來的是List…

用Python寫Link-list,雖然不是不行拉



應該是防呆機制的關係,拿掉再試乙次

2. Code:
# 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
        """        
        rtype = None
        prev = None
        plugs = 0

        while (l1 is not None) or (l2 is not None) or plugs != 0:
            v1 = v2 = 0
            
            if l1 is not None:
                v1 = l1.val
                l1 = l1.next
                
            if l2 is not None:
                v2 = l2.val
                l2 = l2.next
                
            count = v1 + v2 + plugs
            plugs = count / 10
            
            ln = ListNode(count % 10)
            if rtype is None:
                rtype = ln
                prev = rtype
            else:
                prev.next = ln
                prev = prev.next
        
        return rtype

心得:
速度快了一點吧,微妙


沒有留言:

張貼留言