LeetCode 445 - Add Two Numbers II (Medium)
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
方法:按照题意做就可以
time complexity: O(n) space complexity: O(n)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: s1 = self.getNumberString(l1) s2 = self.getNumberString(l2) num = str(int(s1) + int(s2)) dummy = ListNode(0) cur = ListNode(int(num[0])) dummy.next = cur for i in range(1, len(num)): _next = ListNode(int(num[i])) cur.next = _next cur = cur.next return dummy.next def getNumberString(self, l): res = "" cur = l while cur: res += str(cur.val) cur = cur.next return res
浙公网安备 33010602011771号