美文网首页
2018-06-05 - 1st day - Add Two N

2018-06-05 - 1st day - Add Two N

作者: sszhang | 来源:发表于2018-06-06 01:16 被阅读0次

    You are given two non-empty linked lists representing two non-negative integers. 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.
    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.

    # 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
            """ 
            def to_int(l):
                return l.val + 10 * (to_int(l.next) if l else 0)
    
            num3 = to_int(l1) + to_int(l2)
            
            def to_list(val):
                l = ListNode(val % 10)
                if val > 9:
                    l.next = to_list(val / 10)
                return l
                
            return to_list(num3)
    

    相关文章

      网友评论

          本文标题:2018-06-05 - 1st day - Add Two N

          本文链接:https://www.haomeiwen.com/subject/bxipsftx.html