티스토리 뷰

leetcode medium

2. Add Two Numbers

msna 2019. 2. 21. 00:06

https://leetcode.com/problems/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.


양수만으로 이루어진 비어있지 않은 두 링크드 리스트가 있다.

숫자는 역순으로 저장되었고 각 노드에는 한자리의 숫자가 포함되어 있다.

두 숫자를 더하고 링크드 리스트로 반환하라.


두 숫자는 0자체를 제외하고 앞자리에 0을 포함하지 않는다.

※ 숫자 12의 경우(2->1)로 나타낼 수 있는데 이것을 (2->1->0)으로 표현하지 않는다는 의미.



링크드 리스트가 무엇인지 알고 있다면 그다지 어렵지는 않은 문제이다.


더할 값이 들어있는  l1, l2노드를 운행해가면서 값을 더해서 결과 노드 r노드에 넣어나가면 된다.


두 값을 더해서 두자리가 되면 두자리가 되는 수는 다음 노드에서 더해준다.


예제의 테스트 데이터는 자릿수가 똑같은 경우지만 자릿수가 다른 경우가 발생할 수 있으니 상위 자릿수가 null일 수도 있다는 것만 주의하면 될 것 같다.