[READ-ONLY] Mirror of https://github.com/shuuji3/leetcode. 馃搩 Code submitted to LeetCode
leetcode.com/shuuji3/
leetcode
leetcode-solutions
1#
2# @lc app=leetcode id=2 lang=python3
3#
4# [2] Add Two Numbers
5#
6# https://leetcode.com/problems/add-two-numbers/description/
7#
8# algorithms
9# Medium (32.37%)
10# Total Accepted: 1.1M
11# Total Submissions: 3.5M
12# Testcase Example: '[2,4,3]\n[5,6,4]'
13#
14# You are given two non-empty linked lists representing two non-negative
15# integers. The digits are stored in reverse order and each of their nodes
16# contain a single digit. Add the two numbers and return it as a linked list.
17#
18# You may assume the two numbers do not contain any leading zero, except the
19# number 0 itself.
20#
21# Example:
22#
23#
24# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
25# Output: 7 -> 0 -> 8
26# Explanation: 342 + 465 = 807.
27#
28#
29#
30# Definition for singly-linked list.
31# class ListNode:
32# def __init__(self, x):
33# self.val = x
34# self.next = None
35
36class Solution:
37 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
38 carry = 0
39 sum_list: ListNode = None
40 current_list = sum_list
41
42 while True:
43 sum_val = l1.val + l2.val + carry
44 if sum_val >= 10:
45 carry = 1
46 else:
47 carry = 0
48
49 new_list = ListNode(sum_val % 10)
50 if current_list is None:
51 sum_list = new_list
52 else:
53 current_list.next = new_list
54 current_list = new_list
55
56 if l1.next is None and l2.next is None:
57 if carry == 1:
58 new_list = ListNode(1)
59 current_list.next = new_list
60 current_list = new_list
61 break
62 elif l1.next is None:
63 l1.val = 0
64 l2 = l2.next
65 elif l2.next is None:
66 l2.val = 0
67 l1 = l1.next
68 else:
69 l1 = l1.next
70 l2 = l2.next
71
72 return sum_list