Source
https://leetcode.com/problems/plus-one/
Plus One - LeetCode
Can you solve this real interview question? Plus One - 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-
leetcode.com
Code
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function (digits) {
let cnt = 0;
for (let i = digits.length - 1; i >= 0; i--) {
let num = digits.pop();
if (num === 9) {
cnt += 1;
continue;
} else {
digits.push(num + 1);
break;
}
}
if ((cnt !== 0) & (digits.length === 0)) {
digits.push(1);
}
for (let i = 0; i < cnt; i++) {
digits.push(0);
}
return digits
};
How to solve?
1. 마지막 숫자를 pop해준 뒤 만약 9라면 0의 갯수를 의미하는 cnt를 늘려준다.
2. 마지막 숫자가 9가 아니라면 +을 더한 뒤 다시 집어 넣는다.
3. 만약 cnt가 0이 아닌데 digits가 비어 있다면 [9]나 [9, 9]와 같은 경우이기 때문에 1을 넣어준다.
4. cnt의 길이만큼 순회하며 0을 넣어준다.
코드 분석
One line js solution with full explanation, beginner-friendly - Plus One - LeetCode
View bekjonishpulatov8's solution of Plus One on LeetCode, the world's largest programming community.
leetcode.com
그냥 Number 로 했을때는 부동소수점 문제가 발생하였지만 BigInt는 Number가 나타낼 수 있는 최댓값인 2^53 - 1 보다 큰 정수를 표현할 수 있는 내장 객체이기에 아래와 같은 풀이가 가능하다.
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
return (BigInt(digits.join("")) + BigInt(1)).toString().split("");
};
'Problem solve' 카테고리의 다른 글
[Leetcode] 2619. Array Prototype Last (Javascript) (0) | 2023.04.12 |
---|---|
[Leetcode] 13. Roman to Integer (Javascript) (0) | 2023.04.11 |
[Leetcode] 46. Permutation (Javascript) (0) | 2023.04.09 |
[Leetcode] 20. Valid Parentheses (Javascript) (0) | 2023.04.08 |
[Leetcode] Reverse Integer (Javascript) (0) | 2023.04.02 |