LeetCodeOJ:2. Add Two Numbers

来源:互联网 发布:淘宝 新版瑞士军刀 编辑:程序博客网 时间:2024/05/21 06:24
Total Accepted: 129010 Total Submissions: 572407 Difficulty: Medium

You are given two linked lists representing two non-negative numbers. 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.

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


Language:python

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        ans = ListNode(0)        cur = ans        sum = 0                while(True):            if l1 != None:                sum += l1.val                l1 = l1.next            if l2 != None:                sum += l2.val                l2 = l2.next                        cur.val = sum % 10            sum = sum / 10                        if l1 != None or l2 != None or sum != 0:                cur.next = ListNode(0)                cur = cur.next            else:                break                        return ans

0 0
原创粉丝点击