Plus One

Jamie·2022년 2월 28일
0

LeetCode

목록 보기
6/18
post-thumbnail

문제

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:

Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].

Constraints:

1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.

풀이

var plusOne = function (digits) {
    // 마지막 숫자가 9가 아니면 마지막 숫자에만 +1을 해준다
    // 마지막 숫자가 9일경우 반복문을 돌면서
    // 마지막 숫자가 9이거나 해당 인덱스 요소가 10일경우 그 자리수는 0으로 재선언하고 앞자리수에 +1을 해준다
    // 앞자리수가 없을경우 digits에 1을 unshift해준다

    let last = digits.length - 1;
    if (digits[last] !== 9) {
        digits[last] += 1;
    } else {
        for (let i = last; i >= 0; i--) {
            if (digits[last] === 9 || digits[i] === 10) {
                digits[i] = 0;
                if (digits[i - 1] === undefined) {
                    digits.unshift(1);
                } else {
                    digits[i - 1] += 1;
                }
            }
        }
    }
    return digits;
};

❗️ leetcode의 테스트케이스는 생각보다 촘촘했다😹

✅ 처음엔 반복문안에 조건문을 if (digits[i] === 9 || digits[i] === 10) 라고 했는데
생각해보니 이렇게 돌리면 더이상 더하지 안하도 되는 상황인데 요소가 9이면 무조건 1을 더해주게 되어있다.
그래서 if (digits[last] === 9 || digits[i] === 10) 라고 바꿨더니 예외상황도 걸리지 않고 돌아갔다.

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글