问题

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.

Example

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

过程

  • 先算出每个链表代表的数字,进行相加

  • 然后再把得数转换为链表形式

Code

# 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
        """
        l1_num = self.getval(l1)
        l2_num = self.getval(l2)
        l3_num = l1_num + l2_num
        
        l3 = ListNode(l3_num % 10)
        head = l3
        index = 1
        while l3_num / (10 ** index):
            l = ListNode((l3_num / (10 ** index)) % 10)
            head.next = l
            head = l
            index += 1
            
        return l3
            
        
    def getval(self, l):
        num = 0
        index = 0
        while l:
            num += l.val * (10 ** index)
            l = l.next
            index += 1
        return num

努力奋斗的小菲菲
23 声望3 粉丝

小鲜肉一枚


« 上一篇
1. Two Sum