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.
나의 첫 번째 풀이
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
return (Number(digits.join('')) + 1).toString().split('')
};
Wrong Answer
Input
digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
- 위와 같이 풀었을 때 71번째 케이스에서 오류가 났습니다. 왜냐하면 [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]을 join을 통해서 숫자타입으로 변경을 하게되면 bigInt이기 때문에 값이 변형되는걸 알 수 있습니다.
그래서 저는 아래와 같이 코드를 수정하였습니다.
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
return (BigInt(digits.join('')) + BigInt(1)).toString().split('')
};
- BIgInt를 통해서 digits를 join한 값을 감싼 후 BigInt로 감싼(1)을 더한 후 toString을 통해서 문자열로 변환 후 split('')함수를 통해서 나눠진 배열을 return 해주었습니다.
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
공 던지기 (0) | 2023.02.15 |
---|---|
[프로그래머스] 소인수분해 (0) | 2023.02.15 |
[Leet Code - eazy] 1528. Shuffle String (0) | 2023.02.14 |
[Leet Code - eazy] 1389. Create Target Array in the Given Order (0) | 2023.02.14 |
숨어있는 숫자의 덧셈 (2) (0) | 2023.02.14 |