leetcode Add Two Numbers---需要再看

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


understanding:

自己最直观的算法可以做。但又更好的。


参考,  用下面ref的code

http://bookshadow.com/weblog/2015/04/05/leetcode-add-two-numbers/


自己的code效率太低,不过为了赶时间。先这样吧

my code:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        i,j = l1,l2
        flag = -1
        reminder = - 1
        #print (l1.val,l2.val)
        while i or j :
            #print (i.val, j.val)
            tmp = i.val + j.val
            if int(tmp / 10) > 0:
                flag = 1
                reminder = tmp % 10
            else:
                flag = 0
            if not i.next:
                if flag == 1:
                    last = ListNode(flag)
                    i.next = last
                    last.next = None
                    i.val = reminder
                else:
                    i.val = tmp
            else:
                if flag == 1:
                    i.val = reminder
                    i.next.val += 1
                else:
                    i.val = tmp
            pre_i, pre_j = i,j
            i = i.next
            j = j.next
            if not i and j:
                add_node = ListNode(0)
                pre_i.next = add_node
                add_node.next = None
                i = add_node
            if not j and i:
                add_node_2 = ListNode(0)
                pre_j.next = add_node_2
                add_node_2.next = None
                j = add_node_2
                
        return l1



你可能感兴趣的:(leetcode Add Two Numbers---需要再看)