1

I am converting array digits into a number e.g. [1,2,4] = 124.

This code is working for smaller values but when I checked for big values like [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3], I was not able to add the last 543 to my sum.

var plusOne = function(digits) {
    let tsum = 0;
    let sum = 0;
    for (let i = 0; i < digits.length; i++) {
        let k =Math.pow(10, (digits.length - (i + 1)));
        tsum = arr[i]* k;
        console.log(tsum);
        sum = sum + tsum;
        console.log(sum);
    }
    console.log(sum);
    sum= sum + 1;
    let cnt=0;
    while (sum!=0) {
        digits.unshift(Math.floor(sum%10));
        sum = Math.floor(sum/10); 
        cnt++;
    }
    digits.length = cnt;
    return digits;
};
let arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3];
console.log(plusOne(arr)); 
Lauren Yim
  • 12,700
  • 2
  • 32
  • 59
  • 2
    These are large numbers, for this you might need to use `BigInt`. Check this - https://stackoverflow.com/questions/4557509/javascript-summing-large-integers – Darshna Rekha Aug 30 '21 at 04:48

2 Answers2

0

First, join the digits and make a string:

const joined =[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3].join('')
// output: "6145390195186705543"

Second, convert the string to a BigInt:

const number = BigInt(joined)
pesehr
  • 787
  • 2
  • 9
  • 23
0

Your method for adding a one to a an array of digits won’t work for large numbers. JavaScript stores all numbers as a floating point, so as Darshna Rehka and pesehr suggested, you should use BigInt for this. See Issue with combining large array of numbers into one single number for more information.

Although this doesn’t directly answer your question, here’s a different implementation of plusOne that should work for larger numbers:

const plusOne = digits => {
    // Base case: treat empty arrays as 0 so return [1]
    // This part is important for the recursion below
    if (!digits.length) return [1];
    const init = digits.slice(0, -1);
    const last = digits[digits.length - 1];
    return last === 9
        // 9 + 1 = 10, carry the 1 (add 1 to the rest of the digits)
        // If there are no more digits to the left of the 9 (init.length === 0),
        // plusOne(init) will just return [1] (base case)
        ? [...plusOne(init), 0]
        // Simply add 1 to the last digit and keep the rest
        : [...init, last + 1];
};
const arr = [6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3];
console.log(plusOne(arr).join(''));
console.log(plusOne([1, 8, 9]).join(''));
console.log(plusOne([9, 9, 9]).join(''));
Lauren Yim
  • 12,700
  • 2
  • 32
  • 59