码迷,mamicode.com
首页 > 其他好文 > 详细

Add Two Numbers

时间:2016-10-06 21:57:39      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

题目如下:

技术分享

Python代码:

# 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
        """
        head = ListNode(1)
        current = ListNode(1)
        head.next = current
        flag = 0
        while l1!=None and l2!=None:
            sum = l1.val+l2.val+flag
            if sum<10:
                flag = 0
                current.next = ListNode(sum)
            else:
                flag = 1
                current.next = ListNode(sum-10)
            current = current.next
            l1 = l1.next
            l2 = l2.next
        if l1==None and l2!=None:
            print "in"
            while l2!=None:
                if flag==0:
                    current.next = ListNode(l2.val)
                else:
                    if l2.val+1<10:
                        flag = 0
                        current.next = ListNode(l2.val+1)
                    else:
                        flag = 1
                        current.next = ListNode(l2.val-9)
                l2 = l2.next
                current = current.next
        if l1!=None and l2==None:
            print "out"
            while l1!=None:
                if flag==0:
                    current.next = ListNode(l1.val)
                else:
                    if l1.val+1<10:
                        flag = 0
                        current.next = ListNode(l1.val+1)
                    else:
                        flag = 1
                        current.next = ListNode(l1.val-9)
                l1 = l1.next
                current=current.next
        if flag == 1:
            current.next = ListNode(1)
        return head.next.next
a = ListNode(1)
b = ListNode(9)
b.next = ListNode(9)
c = Solution()
c.addTwoNumbers(a,b)

 

Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/CQUTWH/p/5934608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!