What is 32-bit integer in JavaScript?

Solution 1:

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));

More efficient

Conversion to string, splitting and joining are relatively expensive operations in comparison with simple arithmetic operations. And so it will be more time (and memory) efficient to solve the problem like this:

function reverse(n) {
    var reverseN = 0;
    var sign = n < 0;
    n = Math.abs(n);
    while (n) {
        reverseN = reverseN*10 + (n % 10);
        n = Math.floor(n/10);
    }
    return reverseN > 0x7FFFFFFF ? 0 : sign ? -reverseN : reverseN;
}

console.log(reverse(-123));
console.log(reverse(1563847412));

Solution 2:

var reverse = function(x) {
  let ans = parseInt(x.toString().split('').reverse().join('').toString());

  if (x < 0) { ans *= -1; }

  if (ans < (Math.pow(2, 31) * -1) || ans > Math.pow(2, 31) - 1) return 0;
  return ans;
};

console.log("Reverse of 123: " + reverse(123));
console.log("Reverse of -123: " + reverse(-123));

Solution 3:

However, I am stumped with some of the failing tests:

Input:
1563847412
Output:
2147483651
Expected: 0

the max 32-bit integer I believe is (2^31) which is 2,147,483,647. This is so that negative values can be stored as well (-2^31) being the 32 bit limit (this is what "signed" means). So any number higher than that, you can return 0 for the sake of your program. If the prompt asked you for "unsigned", the range would be 0 to 2^32 as you initially assumed.

In terms of your failed test, 2147483651 is 4 greater than 2,147,483,647 so you should return 0. Instead you should say reverseX > Math.pow(2,31) - 1

What is its significance in JS and what happen if I started going over? (2^32 + 1)

Technicially in JS you aren't restricted by this number, JS uses significand double-precision floating point numbers. So the max value is actually (2^53) - 1

Solution 4:

var reverse = function(x) {
    var reverseX = parseInt(x.toString().split('').reverse().join(''));
    if (reverseX < (Math.pow(2, 31) * -1) || reverseX > Math.pow(2, 31) - 1) return 0;
    return reverseX* Math.sign(x);
    
};
  • First convert x into string and split it with '' so you will get array.

  • Later use reverse() function of array to reverse element of an array

  • After than join again using join('') function Now, Check If reversing reverseX causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

    if (reverseX < (Math.pow(2, 31) * -1) || reverseX > Math.pow(2, 31) - 1) return 0;

Solution 5:

Unfortunately, all solutions posted so far (except, maybe this one) are incorrect! Including currently accepted solution. Here is why.

32-bit integer has range from -2147483648 (-2^31) to 2147483647 (2^31 − 1)

Therefore, if we pass into our reverse function

  • -8463847412 - we should get -2147483648 (which is still in the range), but in most solutions posted here, we get 0, which is wrong!
  • 8463847412 - we should get 0. Some solutions posted here fail this, instead showing 2147483648 which is above max 32-bit integer limit.

Here is my solution, maybe not most elegant, but for sure most accurate

// feel free to use exact values here to optimize performance
const minIntegerNumber = Math.pow(-2, 31) // -2147483648
const maxIntegerNumber = Math.pow(2, 31) - 1 // 2147483647

function reverse(x: number): number {
  const reversedCharacters = x.toString().split('').reverse().join('')
  if (x < 0) {
    const result = Number(`-${reversedCharacters.slice(0, reversedCharacters.length - 1)}`)
    return result < minIntegerNumber ? 0 : result
  } else {
    const result = Number(reversedCharacters)
    return result > maxIntegerNumber ? 0 : result
  }
}