Search code examples
javascriptarraysbigint

Javascript Type Error: Cannot mix BigInt and other types, use explicit conversions


I was trying to add a individual digits of an BigInt number to an array. When I did that I encountered the above error.

Below is the code Snippet:
var plusOne = function(digits) {
    const outputValue = BigInt(digits.join("")) + 1n;
    let arr = [];
    while(outputValue > 0)
    {
        arr.push(BigInt(outputValue%10));
        outputValue = BigInt(Math.floor(outputValue/10));
    }
    return arr;
};
  

  console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3])); 

Can you please tell me what am I doing wrong?

I tried making the push into the array as a BigInt but it never worked. I want to add the individual digits to the array from the BigInt Number.


Solution

  • I believe this is what you wanted:

    var plusOne = function(digits) {
        let outputValue = BigInt(digits.join("")) + 1n; // changed const to let
        let arr = [];
        while(outputValue > 0)
        {
            arr.push(BigInt(outputValue%10n)); // changed 10 to 10n 
            outputValue = BigInt(outputValue/10n); // changed 10 to 10n and removed Math.Floor
        }
        return arr;
    };
    console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
    

    First of all you need to use x%10n and x/10n when working with BigInt numbers (essentially suffix the values with an n)

    Secondly you dont need to use Math.Floor on this operation and it also wont work as BigInts can not be converted to a number. Read more about it in this stackoverflow question

    Lastly you need to declare the outputValue with let because you are modifying its value later