Study/Algorithm
[leetcode] 2. add two numbers
DoRoMii
2019. 8. 7. 17:26
728x90
2. Add Two Numbers
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 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):
result = None
tail = None
carry = 0
while l1 is not None or l2 is not None or carry != 0 :
l1_num = l1.val if l1 else 0
l2_num = l2.val if l2 else 0
if result is None :
result = ListNode((l1_num + l2_num + carry)%10)
tail = result
else :
tail.next = ListNode((l1_num + l2_num + carry)%10)
tail = tail.next
carry = 0 if l1_num + l2_num + carry < 10 else 1
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return result
* 실수한 부분
l1 과 l2가 없어도 carry가 있으면 연산을 해야하는데 그부분을 간과함
carry 만들때도 l1_num + l2_num + carry를 해야했는데 carry를 빠뜨렸음.