02.Add Two Numbers

来源:互联网 发布:jquery获取form数据 编辑:程序博客网 时间:2024/06/09 16:53

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


python:

# Definition for singly-linked list.

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    # @param {ListNode} l1
    # @param {ListNode} l2
    # @return {ListNode}
    def addTwoNumbers(self, l1, l2):
        out=p=ListNode((l1.val+l2.val)%10)
        quot=(l1.val+l2.val)/10
        while l1.next!=None and l2.next!=None:
            l1=l1.next
            l2=l2.next
            q=ListNode((l1.val+l2.val+quot)%10)
            p.next=q
            p=p.next
            quot=(l1.val+l2.val+quot)/10
        while l1.next!=None:
            l1=l1.next
            q=ListNode((l1.val+quot)%10)
            quot=(l1.val+quot)/10
            p.next=q
            p=p.next
        while l2.next!=None:
            l2=l2.next
            q=ListNode((l2.val+quot)%10)
            quot=(l2.val+quot)/10
            p.next=q
            p=p.next
        if quot!=0:
            q=ListNode(quot)
            p.next=q
            p=p.next
        return out
0 0
原创粉丝点击