바위타는 두루미

[leetcode] 2. add two numbers 본문

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를 빠뜨렸음.

'Study > Algorithm' 카테고리의 다른 글

[leetcode]94. Binary Tree Inorder Traversal  (0) 2019.08.09
[leetcode]160. Intersection of Two Linked Lists  (1) 2019.08.08
[프로그래머스]도둑질  (3) 2019.08.01
[프로그래머스]단어변환  (0) 2019.08.01
[LeetCode] 91. Decode way  (0) 2019.07.29
Comments