Python实现Leetcode------2. 两数相加

2. 两数相加


题目链接:点我


思路:

方法1 将l1 和 l2 分别转换为数值,然后求和,在将其转换为ListNode
方法2 将l1 和l2 的每一位一次计算,将计算的结果直接插入到ListNode 中

采用第二种方法

# -*- coding: utf-8 -*-
"""
Created on Tue Jun  5 17:18:23 2018

@author: Administrator
"""
class ListNode:
     def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        ans = ListNode(0)
        temp = ans
        tempsum = 0

        while True:
            if (l1 != None):
                tempsum = l1.val + tempsum
                l1 = l1.next
            if (l2 != None):
                tempsum = tempsum + l2.val
                l2 = l2.next

            temp.val = tempsum % 10
            tempsum  = int(tempsum / 10)

            if l1 == None  and l2 == None and tempsum == 0:
                break

            temp.next = ListNode(0)
            temp = temp.next

        return ans





if __name__ == "__main__":
    t1 = ListNode(3)
    t2 = ListNode(4)
    t2.next = t1
    t3 = ListNode(2)
    t3.next = t2


    b1 = ListNode(4)
    b2 = ListNode(6)
    b2.next = b1
    b3 = ListNode(5)
    b3.next = b2

    result = Solution()
    add_sum = result.addTwoNumbers(t3, b3)

    while (add_sum != None):
        print (add_sum.val)
        add_sum = add_sum.next
View Code

 

posted @ 2018-06-05 19:58  NaLaEurCAS  阅读(1957)  评论(0编辑  收藏  举报