막무가내로 삽질하는 알고리즘

PlusOne

Jungsoomin :) 2020. 10. 25. 16:23
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1: Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.

 

  • list 를 사용하지 않는 문제.
  • 첫 원소가 9 가 되면 새배열 생성
  • 분기에 따른 리턴
/**
     * for 문을 거꾸로 돌려서 9 인지 아닌지 판단
     * 9라면 0 으로 만들고 다음 으로
     * 9가 아니라면 1 더하고 break;
     * 만약 마지막 원소가 9라면 첫 원소에 1 추가
     *
     * @param input
     */
    private static void solve(int[] input) {

        int val = 0;
        int[] answer = null;
        for (int i = input.length - 1; i >= 0; i--) {
            val = input[i];
            if (i != 0 && val == 9) {
                input[i] = 0;
                continue;
            } else if (i == 0 && val == 9) {
                input[i] = 0;
                answer = new int[input.length + 1];
                answer[0] = 1;
            } else {
                input[i] = val + 1;
                break;
            }
        }
        if (answer == null) {
            System.out.println(Arrays.toString(input));
        } else {
            System.out.println(Arrays.toString(answer));
        }
    }

  • 조건을 잘 생각해야 한다.
  • for 문 역순 탐색은 동일
  • 분기 점에서 input[i] 가 9인 조건은 걸어둘 필요가 없다. 왜냐하면, i == 0 인 if 문에 걸리는 조건은 모든 원소가 9일경우 밖에 없기 때문이다.
  • 새로운 배열의 기본 값은 0 이므로, 첫 원소에 1만 추가해주면 된다.
private static int[] solve(int[] input) {
        int[] res = null;
        // for, while
        for (int i = input.length - 1; i >= 0; i--) {
            if (input[i] != 9) {
                input[i]++;
                break;
            }
            if (i == 0) {
                // 새로운 인트배열은 기본값이 "0" 임, i 가 0 이라는 건 원소들이 다 9라는 이야기 와 같음 따라서 input 이 9 인지는 비교할 필요가 없다.
                res = new int[input.length + 1];
                res[0] = 1;
                return res;
            }
        }

        return input;
    }

'막무가내로 삽질하는 알고리즘' 카테고리의 다른 글

Longest Substring With At Most Two Distinct  (0) 2020.10.26
UniqueEmailAddresses  (0) 2020.10.25
KClosest  (0) 2020.10.25
다리를 지나는 트럭  (0) 2020.10.19
LicenseKeyFormatting  (0) 2020.10.18