두 개의 음수가 아닌 정수를 나타내는 비어 있지 않은 연결 리스트가 주어진다.
자릿수는 역순으로 저장되며 각 노드는 한 자릿수를 포함한다.
두 숫자를 추가한 후 링크된 목록으로 반환하십시오.
0이라는 숫자 자체를 제외하고 두 숫자에 선행 0이 포함되어 있지 않다고 가정할 수 있다.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode answer = new ListNode(0);
ListNode tmp = answer;
int carry = 0;
while (l1 != null || l2 != null) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
// 자릿수 변환
if (sum >= 10) {
answer.next = new ListNode(sum - 10);
carry = 1;
} else {
answer.next = new ListNode(sum);
carry = 0;
}
answer = answer.next;
}
if (carry == 1) {
answer.next = new ListNode(1);
}
return tmp.next;
}