[leetcode445】Add Two Numbers II

来源:互联网 发布:人工智能 图书 编辑:程序博客网 时间:2024/06/06 00:40

1解题思想:将链表转为数字 7-2-3-4转为7234,1-2转为12,然后将数字对应相加,再将结果7246通过取余一个一个(6,4-6,2-4-6,7-2-4-6)放进一个链表7-2-4-6里。

2.另一种解题思路是将两个链表反转后相加得到

# 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
        """
        a=0
        b=0
        while l1:
            a=a*10+l1.val
            l1=l1.next
        while l2:
            b=b*10+l2.val
            l2=l2.next
        sum=a+b
        res=head=ListNode(0)
        if sum==0:return head
        while sum:
            remainder=sum%10
            sum=sum//10
            head.next,head.next.next=ListNode(remainder),head.next
            
        return res.next
0 0
原创粉丝点击