-2

This is the question: https://leetcode.com/problems/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.

This is my code:

var plusOne = function(digits) {
    let num = 0;
    
    for(let i = 0; i < digits.length; i++){
        num += digits[i] * (10 ** (digits.length-i-1))
    }
    
    return (num+1).toString().split("").map(Number)
}; 

Failed test case:

Input:
[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]

I realised that the code also works fine as long as digits.length <= 17, for e.g. [1,2,3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7] Once there are 18 numbers in digits for e.g. [1,2,3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8] it stops working and I can't seem to find the bug with this. Can someone please help enlighten me? Thank you!!

deceze
  • 491,798
  • 79
  • 706
  • 853
ccc6
  • 1
  • 2
  • 1
    Does this answer your question? [What is JavaScript's highest integer value that a number can go to without losing precision?](https://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin) – Ivar May 31 '22 at 12:07
  • You'll have to come up with a different approach. Converting to number isn't going to work because of insufficient precision. – James May 31 '22 at 12:13
  • 1
    That's exactly the point of this exercise; the straight forward built-in tools don't work. You need to increment each digit by hand… – deceze May 31 '22 at 12:15
  • thanks so much for the tips guys! – ccc6 May 31 '22 at 12:15
  • Here's an approach one might take: Iterate from the least-significant and check if incrementing a digit will cause a `+1` carry-forward. If yes, safe-keep the carry for the next iteration and account for it when incrementing. – jsN00b May 31 '22 at 12:21
  • 1
    When I did this, I started at the back of the array and worked out how many 'trailing 9s' there were, then I swapped them all the 0s and incremented the array item before all the trailing 9s. You just have to be mindful of when the whole array is 9s and handle that – Brett East May 31 '22 at 13:15

0 Answers0