재귀로 풀어야 한다는 소식을 듣고 풀이 방향 전격 변경 !!
1. 두 ListNode를 동시에 돌린다.
- 동시에 현재 노드값, 받아올림 값을 더한다(sum)
- sum이 10보다 큰지 확인한다. (곱이 아니라 합이므로 10 안에서 해결 가능)
- 받아올림 상황(sum / 10 == 1하면 될 듯): 받아올림을 위해 carry++를 해준다
- 받아올림이 아닌 상황: carry에 +1을 추가하지 않는다.
- ans ListNode 현재 노드에 sum%10한 값을 넣는다.
- return 값으로 node 두 개와 carry를 넣는다. (고민되는 부분: carry 대신 sum을 넣어도 괜찮지 않을까?)
- 한쪽 노드가 이미 끝난 경우
- if문을 사용해서 sum 처리하고 바로 return시킨다.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
// 새로운 목표: 무조건 재귀 1회 이상 사용
class Solution {
ListNode dummy = new ListNode(0);
ListNode ans = dummy;
ListNode a = new ListNode(0);
ListNode b = new ListNode(0);
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
a.next = l1;
b.next = l2;
if (plusNode(0) == 1){
ans.next = new ListNode(1);
return dummy.next;
}else{
return dummy.next;
}
}
public int plusNode(int carry){
int sum = 0; // 나중에 옮기기 -> 옮기면 안돼!
if (a.next == null || b.next == null){ // 한쪽 노드가 이미 끝난 경우
if(a.next == null && b.next == null){
return carry;
}else if(a.next == null){
sum = b.next.val + carry;
b = b.next;
ans.next = new ListNode(sum % 10);
ans = ans.next;
return plusNode(sum / 10);
}else{ // b.next == null
sum = a.next.val + carry;
a = a.next;
ans.next = new ListNode(sum % 10);
ans = ans.next;
return plusNode(sum / 10);
}
}else{
sum = a.next.val + b.next.val + carry;
if (sum / 10 == 1){ // 받아올림 상황
ans.next = new ListNode(sum % 10);
ans = ans.next;
a = a.next;
b = b.next;
return plusNode(1);
}else{ // 받아올림 아님 상황
ans.next = new ListNode(sum % 10);
ans = ans.next;
a = a.next;
b = b.next;
return plusNode(0);
}
}
}
}