66. Plus One

Plus One

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-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.

Approach) Brute Force

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    let carry = 1;
    for(let i=digits.length-1;i>=0;i--){
        if(carry > 0){
            let sum = digits[i] + carry;
            if(sum > 9){
                digits[i] = sum - 10;
                carry = 1;
            }else{
                digits[i] = sum;
                carry = 0;
            }
        }
    }
    if(carry == 1){
        return [1,...digits];
    }
    return digits;
};

Approach) Brute Force - Direct

var plusOne = function(digits) {
for(var i = digits.length - 1; i >= 0; i--){
     digits[i]++; 
    if(digits[i] > 9){
        digits[i] = 0;
    }else{
        return digits;
    }
}
digits.unshift(1);
return digits;
};

First, I add 1 anyway. If there is a carry-over, the new digit will also add 1. If the current digit is less than 9 then return the array.

Last, when running over for a loop, I just put fill 1 in front of the array.



Approach) Using BigInt

var plusOne = function(digits) {
    const fromArray = digits.join(''); // get Digits out of Array
    const toInt = BigInt(fromArray) ; //Dont use parseInt, use BigInt instead :) 
    const addOne = toInt + 1n; // add one! 
    const result =  Array.from(String(addOne), Number); // return digits to array
    return result
    
};

Conclusion

That’s all folks! In this post, we solved LeetCode problem 66. Plus One

I hope you have enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.


In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!


Comments

Popular Post