[LeetCode] 66. Plus One
Coding Test

[LeetCode] 66. Plus One

Given a non-empty array of decimal digits representing a non-negative integer, increment 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 contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:
Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:
Input: digits = [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
Example 3:
Input: digits = [0] Output: [1]

배열이 주어지면 1을 더해서 숫자를 만드는 문제입니다. Easy 난이도로 매우 쉬운거 같은데요. 하나만 조심하면 될 거 같습니다.

바로 자릿수를 넘어가는 경우입니다. 숫자9를 만나면 결과가 10이기 때문에 배열의 범위를 넘어가게 되겠네요.

 

저는 List를 선언하여 따로 값을 넣어주고 결과 반환 시 다시 배열로 만들도록 하였습니다.

 

아래는 전체 소스코드 입니다.

public class PlusOne {
    public int[] plusOne(int[] digits) {
        List<Integer> result = new LinkedList<>();

        for (int i = digits.length - 1; i >= 0; i--) {
            if (digits[i] == 9 && i == 0) {
                result.add(1);
            }

            if (digits[i] == 9) {
                digits[i] = 0;
                continue;
            }

            digits[i] = digits[i] + 1;
            break;
        }

        result.addAll(Arrays.stream(digits).boxed().collect(Collectors.toList()));
        return result.stream().mapToInt(i -> i).toArray();
    }
}

숫자가 9이고 제일 앞자리라면 List에 1을 미리 넣어주도록 합니다.

 

다음은 순회하면서 덧셈을 할텐데요. 9를 만나지 않으면 그냥 멈춰서 1만 더해주면 됩니다.

간단했네요.