2019년 5월 16일 목요일

[leetcode] 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.

번역)

당신은 두개의 양수값을 보여주는 연속된 링크드 리스트를 제공받는다.
숫자들은 역순으로 배열되어있고, 각 노드 마다 1자리씩 들어가 있다.
2개의 숫자를 더해서 그것을 링크드 리스트로 반환하여라

Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.


문제접근

342 + 465 = 807
이를 역순으로 들어가 있는데, 역순으로 들어가 있다.

답은 각 링크드리스트의 요소들의 합이다.
1의 자리부터 순차적으로 링크드리스트의 값을 순회하여 더해주고
만약 10이 넘어가면 값을 캐시해두었다가 다음 next값에 더해주면 된다.
값이 0보다 크면 해당 값에대한 node를 만들어 답 링크드리스트에 append해준다.


소스코드


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        answer = ListNode(0)
        current = answer
        carry = 0
        while True:
            value = 0
            if l1:
                value += l1.val
                l1 = l1.next
            if l2:
                value += l2.val
                l2 = l2.next
            
            value += carry
            current.next = ListNode(value % 10)
            carry = value // 10
            current = current.next
            
            if l1 is None and l2 is None:
                break
        
        if carry > 0:
            current.next = ListNode(carry) 
        return answer.next
            
            

댓글 없음:

댓글 쓰기