Skip to content

Latest commit

 

History

History
91 lines (70 loc) · 2.2 KB

File metadata and controls

91 lines (70 loc) · 2.2 KB

Try it on LEETCODE

Challenge

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.

Evaluation

Inputs

We are given a single input, an array of integers.

Constraints

We know that the length of digits array will be between 1 and 100 (inclusive).
We know that any single digit will be between 0 and 9.
We know that the array will not have a 0 in the first index.

Initial Thoughts

Turn the digits array into an integer, add one, then turn it back into an array of integers.

Approach

First we will joing the digits into a string.

We will then convert that string into a BigInt, handling any case where the integer is to large for number type.

Next we will add BigInt 1 to the previous BigInt.

Finally we coherce the number into a string again and split it. We return this.

Complexity

Time: $$O(n)$$
Space: $$O(n)$$

Code

Javascript:

/**
 * Echos out what you put in.
 * Runs at o(n)
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    var numString = digits.join('');
    var numInt = BigInt(numString);
    var plusOne = numInt+BigInt(1);
    return (''+plusOne).split('')
};