원티드 프리온보딩 - BE/과제 정리

[LinkedList] 2. Add Two numbers

고마우미 2023. 8. 29. 02:57

문제 

두 개의 음수가 아닌 정수를 나타내는 두 개의 비어 있지 않은 연결 목록이 제공됩니다. 숫자는 역순으로 저장되며 각 노드에는 단일 숫자가 포함됩니다. 두 숫자를 더하고 그 합계를 연결된 목록으로 반환합니다.
숫자 0 자체를 제외하고는 두 숫자에 선행 0이 포함되어 있지 않다고 가정할 수 있습니다.

Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:
Input: l1 = [0], l2 = [0] Output: [0]

Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
 
Constraints:
The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.

 

문제 접근

  1. l1 노드와 l2 노드의 value 값을 더한다.
  2. value 값이 10을 넘으면 다음 노드의 합에 1을 추가해준다.
  3. 다음노드를 연결해준다

 

문제 풀이

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode headNode = new ListNode();
        ListNode currentNode = null;
        ListNode nextNode = null;
        
        int sum = 0;
        int plus = 0;

        boolean isFirst = true;

        while( l1 != null || l2 != null){

            if(l1 != null) sum += l1.val;
            if(l2 != null) sum += l2.val;

            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
           
            currentNode = nextNode;

            if(isFirst){
                headNode.val = sum % 10;
                  nextNode = new ListNode();
                  headNode.next = nextNode;
                isFirst = false;
            }else{
                currentNode.val = (sum + plus) % 10;
                  nextNode = new ListNode();
                  currentNode.next = nextNode;
            }

            if(sum + plus >= 10) plus = 1;
            else plus = 0;
            sum = 0;
        }

        if(plus == 1){
            nextNode.val = 1;
        }else{
            if(currentNode != null) currentNode.next = null;
            else headNode.next = null;
            nextNode = null;
        }

        
        return headNode;
    }
}

 

다른풀이 및 회고

 

예외케이스를 생각하지 않았지만 수정을 통해 정상적으로 수행되었다.

1개 이상의 노드에서 null인경우 처리를 생각하지 못하고 코드를 짜다가 코드가 많이 난잡해졌다.

단순히 풀이 방법 뿐만 아니라 예외케이스에 대한 대비도 잘해야할것 같다.