[LeetCode][Java] Add Two Sum

최지수·2021년 9월 25일
0

Algorithm

목록 보기
6/77
post-thumbnail

오랜만에 Linked List를 활용하는 문제였습니다. 크게 어려운 것은 없었으나 제한 사항을 제대로 보지 못했고, 익숙하지 않은 언어로 풀다 보니 많이 헤맸어요.

문제

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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

예제

제한 사항

  • 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.

접근

단순히 같은 노드 레벨에 있는 요소들 끼리 더하고 10을 넘어가면 해당 값을 다음 레벨 노드에 더하는 방식으로 접근하면 되는 문제였습니다.

처음 접근할 때 리스트를 통해 숫자를 구성하고 더한 다음에 리스트를 구성하는 방식으로 접근했습니다만, 리스트의 범위가 100까지 이루어질 수 있다는 것을 간과했습니다... 이렇게 되면 100자리 숫자가 구성되어 버리는 문제가 생겼어요.

BigInteger를 제대로 사용할 수 있었다면 되지 않았을까 생각되었지만, 활용 방식이 다소 복잡하여 리스트 내부 같은 노드들 끼리 더하고 두 자릿수 이상의 숫자는 10을 나누어 다음 노드 연산 과정에 더하는 방식으로 전개했습니다.

답안

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(null == l1 && null == l2)
            return new ListNode(0);

        ListNode answer = new ListNode();
        ListNode tmpNode = answer;
        int nextUp = 0;
        while(null != l1 || null != l2){
            if(null != l1){
                tmpNode.val += l1.val;
                l1 = l1.next;
            }
            if(null != l2){
                tmpNode.val += l2.val;
                l2 = l2.next;
            }

            if(nextUp > 0) {
                tmpNode.val += nextUp;
            }

            if(tmpNode.val >= 10){
                nextUp = tmpNode.val / 10;
                tmpNode.val %= 10;
            }
            else{
                nextUp = 0;
            }

            if(null != l1 || null != l2){
                tmpNode.next = new ListNode();
                tmpNode = tmpNode.next;
            }
        }

        if(nextUp > 0){
            tmpNode.next = new ListNode();
            tmpNode.next.val = nextUp;
        }

        return answer;
    }
}

후기

문제를 꼼꼼히 읽어보는 습관을 길러야겠습니다. 간단하면서 '그냥 연습 문제니까'라는 마인드로 접근해 문제 푸는데 시간이 오래 걸린듯 합니다. 이 부분을 주의하면서 연습을 해야겠습니다 ㅎㅎ

profile
#행복 #도전 #지속성

0개의 댓글