
❓ 문제
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.
정수 배열 자릿수로 표현되는 큰 정수가 주어진다. 여기서 각 자릿수[i]는 정수의 i번째 자릿수입니다.
숫자는 왼쪽에서 오른쪽 순서로 최상위에서 최하위 순으로 정렬된다. 큰 정수에는 선행 0이 포함되지 않습니다.
주어진 수를 1씩 증가시키고 결과 숫자 배열을 반환한다.
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].
❗ 내 풀이
실제로 계산하는 것처럼 해당 자릿수 + 1을 했을 때 10이 이상이면 다음 자릿수에 1을 올려주는 방식으로 재귀함수를 사용하였다.
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
let index = digits.length - 1;
let lastNum = digits[index];
digits[index] += 1;
if(digits[index] < 10) {
return digits;
} else {
return roundUpNumber(digits, index);
}
};
function roundUpNumber(digits, index) {
let quotient = digits[index] / 10;
let remainder = digits[index] % 10;
if(index == 0) {
digits[index] = remainder;
digits.unshift(quotient);
} else {
digits[index - 1] += quotient;
digits[index] = remainder;
if(digits[index - 1] >= 10) {
digits = roundUpNumber(digits, index - 1);
}
}
return digits;
}
Runtime: 79 ms
Memory Usage: 41.9 MB
❗ Runtime이 가장 빨랐던 답변과 비교
var plusOne = function(digits) {
const str = digits.reduce((a, b) => `${a}${b}`);
const bInt = BigInt(str);
return (bInt+1n).toString().split('');
};
1n - 정수 리터럴 끝에 n을 붙이면 BigInt 타입의 값으로 만들 수 있다.
BigInt는 Number 원시 값이 안정적으로 나타낼 수 있는 최대치인 2^53 - 1보다 큰 정수를 표현할 수 있는 내장 객체이다.
BigInt와 Number의 차이점
- BigInt는 내장 Math 객체의 메서드와 함께 사용할 수 없고, 연산에서 Number와 혼합해 사용할 수 없다.
아래 코드들과 위 코드를 이해하기 위해 정리하였다.
toString(10) - 10진수로 문자로 변환하는 함수
digits = [1,2,3,4]
digits.toString(10) -> "1,2,3,4"
digits.toString(10).split(',') -> ["1", "2", "3", "4"]
digits.toString(10).split(',').reduce((a,b)=>a+b) -> "1234"
❗ Memory 사용이 가장 적었던 답변과 비교
var plusOne = function(digits) {
let r = digits.toString(10).split(',').reduce((a,b)=>a+b)
r = BigInt(r)+1n
return r.toString(10).split('')
};
❗ 또 다른 답변과 비교
var plusOne = function(digits) {
const str = digits.join('')
let sum = BigInt(str)+1n;
return sum.toString().split('');
};
🚩 Detail
- 날짜 : 2022.06.15
- 난이도 : Easy
- 제목 : Plus One
- URL : https://leetcode.com/problems/plus-one/
'알고리즘 > 문제풀이' 카테고리의 다른 글
[LeetCode] 70. Climbing Stairs (Easy) 풀이 (1) | 2022.07.06 |
---|---|
[LeetCode] 69. Sqrt(x) (Easy) 풀이 (0) | 2022.06.20 |
[백준알고리즘] 10815. 숫자 카드 풀이 (Java) (2) | 2022.06.10 |
[백준알고리즘] 7568. 덩치 풀이 (Java) (0) | 2022.04.26 |
[백준알고리즘] 2231. 분해합 풀이 (Java) (1) | 2022.04.25 |