링크 : https://leetcode.com/problems/plus-one/description/
문제 설명
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.
문제 풀이
digits.length가 100이 넘어가므로 일반적인 정수형으로 변환하여 해결하기는 불가능, overflow 발생
따라서 digits배열을 그대로 이용하는 방법으로 해결
1. 마지막 자리에 + 1을 해줌
2. 현재 index(마지막부터 시작)을 기준으로 10보다 크거나 같다면 앞자리로 올려야 함 (올리면서 그 다음 수도 10이 넘어갈 수 있으므로 while로 진행)
3. 올리려는 수 (carry)가 존재할 때 만약 digits의 앞이 더이상 존재 하지 않을 때 (즉, index가 0일 때는 -1자리에 넣어야 함)는 배열에 맨 앞에 추가할 수 있는 `unshift()` 메서드를 이용하여 추가
4. index 앞을 다시 비교하기위해 index - 1
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
digits[digits.length - 1] += 1;
let index = digits.length - 1;
while (digits[index] >= 10) {
const carry = Math.floor(digits[index] / 10);
digits[index] %= 10;
if (index - 1 < 0) {
digits.unshift(carry);
} else {
digits[index - 1] += carry;
}
index--;
}
return digits;
};
결론
정수형으로 변환하여 해결하는 방법이 아닌 배열을 이용하여 각 자리를 계산하여 10초과하면 1을 올리는 방식으로 로직 구성
또한, 배열의 맨 앞이 더 이상 없다면 `unshift()` 메서드를 이용하여 배열 앞에 추가
시간 복잡도 : O(n)
'코딩테스트 > LeetCode' 카테고리의 다른 글
| LeetCode Sqrt(x) (JavaScript) (1) | 2025.12.08 |
|---|---|
| LeetCode Add Binary (JavaScript) (0) | 2025.11.27 |
| LeetCode Spiral Matrix (JavaScript) (0) | 2025.11.26 |
| LeetCode Maximum Subarray (JavaScript), DP (0) | 2025.11.26 |
| LeetCode Group Anagrams (JavaScript) (0) | 2025.11.26 |