What is 32-bit integer in JavaScript? What is 32-bit integer in JavaScript? javascript javascript

What is 32-bit integer in JavaScript?


The upper bound of a signed integer is not 232 - 1, but 231 - 1, since the first bit is the sign bit.

If you make that comparison, you'll see your test gives the right result.

Be aware that JavaScript uses IEEE-754 floating point representation for numbers, even when they are integers. But the precision of floating point is more than enough to perform exact calculations on 32-bit integers. As you realised, you'll need to make the necessary test to detect 32-bit overflow.

Some notes about your code: it passes an argument to the Array#reverse method, which is a method that does not take an argument. Here is how I would write it -- see comments in code:

// Name argument n instead of x, as that latter is commonly used for decimal numbers function reverse(n) {    // Array#reverse method takes no argument.    // You can use `Math.abs()` instead of changing the sign if negative.    // Conversion of string to number can be done with unary plus operator.    var reverseN = +String(Math.abs(n)).split('').reverse().join('');    // Use a number constant instead of calculating the power    if (reverseN > 0x7FFFFFFF) {        return 0;    }    // As we did not change the sign, you can do without the boolean isNegative.    // Don't multiply with -1, just use the unary minus operator.    // The ternary operator might interest you as well (you could even use it    //    to combine the above return into one return statement)    return n < 0 ? -reverseN : reverseN;}console.log(reverse(-123));console.log(reverse(1563847412));