Iggy
Iggy

Reputation: 5251

What is 32-bit integer in JavaScript?

I was doing some coding challenges and encountered something I am not too familiar with. I am more curious to learn what it is and why it is there.

The prompt is pretty straightforward:

Given a 32-bit signed integer, reverse digits of an integer.

Example:
Input: -123
Output: -321

Example:    
Input: 120
Output: 21

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

I came up with this.

var reverse = function(x) {
    var isNegative = false;
    if(x < 0){
        isNegative = true;
        x *= -1;
    };
    var reverseX = parseInt(String(x).split('').reverse((a,b) => a - b).join(''));
    if(reverseX > Math.pow(2,32)){
      return 0;
    }
    if(isNegative){
        return -1 * reverseX
    } else {
        return reverseX;
    }
};

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

Input:
1563847412
Output:
2147483651
Expected: 0

To my understanding, 32 bit integer is 2^32. What is its significance in JS and what happen if I started going over? (2^32 + 1)

My second question, if I may ask two, is I "anticipated" if value of reverseX exceeds 2^32, but it is still failing the test.

if (reverseX > Math.pow(2, 32)) {
  return 0;
}

How can I appropriately return 0 when I exceeded 32-bit integer?

Upvotes: 62

Views: 77609

Answers (20)

Mohan kumar
Mohan kumar

Reputation: 11

var reverse = function(x) {
    const minIntegerNumber = Math.pow(-2, 31) // -2147483648
const maxIntegerNumber = Math.pow(2, 31) - 1 // 2147483647
  const reversed = x.toString().split('').reverse().join('');
  const res = parseInt(reversed) * Math.sign(x)
  console.log(reversed)
   if (res <minIntegerNumber ) {
        return 0;
    }
    else if(res >maxIntegerNumber){
        return 0;
    }
  return res;
  
};

Upvotes: 0

RSol
RSol

Reputation: 23

Pretty easy solution with JS Destructuring

const reverse = (x) => {
    if (x < 10 && x > -10) {
        return x
    }
    if (x >= 0) {
        const rev = +([...`${x}`].reverse().join(''))
        return rev > 0x7FFFFFFF ? 0 : rev
    }
    const rev = +([...`${-x}`].reverse().join(''))
    return rev > 0x7FFFFFFF ? 0 : -rev
};

It can be written shorter, but this solution has:

Runtime: 72 ms, faster than 96.87% of JavaScript online submissions for Reverse Integer. Memory Usage: 43.3 MB, less than 94.52% of JavaScript online submissions for Reverse Integer.

P.S. Thank @trincot for 0x7FFFFFFF

Upvotes: 0

ANUPAMA NETKE
ANUPAMA NETKE

Reputation: 1

let output = 0;
// convert input into its absolute value to make it easier for //calculation
let input = Math.abs(x)

// some math calucation to get last digits of input so that can be //used to reverse a string
while (input > 0) {
  output = (output * 10) + input % 10
  input = Math.floor(input / 10)
}
if (output > Math.pow(2,31)) {
  return 0;
}
// this to check if we need to add '-' to output
if (x < 0) {
  return output * -1
}

return output;

Upvotes: -1

Ayush Soni
Ayush Soni

Reputation: 1

Two-liner shorthand

var reverse = function(x) {
    let remainder = parseFloat(x.toString().split("").reverse().join(""));
    return (remainder >= 2147483647 || remainder <= -2147483648) ? 0 : remainder * Math.sign(x);
};

Upvotes: 0

Erick Vivas
Erick Vivas

Reputation: 35

I came with this. Not as good as some of the other answers but it works.

    function reverse(x) {
        if(x>0){
            x=x.toString();
            var v=1;    
        }
        else{
            x= -1*x;
            x= x.toString();
            var v=-1;
        }
        var newArr = [];
        for(var i=x.length-1;i>=0;i--){
            var index = x.length-1-i;
            newArr[index]=x[i];
        }
        var result = parseInt(newArr.join('')*v);
        if(result <=2147483647 && result >= -2147483647){
            return result
        }
        else{
            return 0
        }
    };

Upvotes: 1

Ihor
Ihor

Reputation: 3809

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
  }
}

Upvotes: 3

Ravi Kant Sharma
Ravi Kant Sharma

Reputation: 1

Here's how I'd do it.

var reverse = function(x) {
    let negative = x < 0;
    x = parseInt(String(Math.abs(x)).split("").reverse().join(""));
    return x > 0x7FFFFFFF ? 0 : negative ? -x : x;
};

Upvotes: 0

PatronusSeeker
PatronusSeeker

Reputation: 61

Here is my solution

 var reverse = function(x) {


    rev_string = x.toString()
    strArray = rev_string.split("")
    revArray = strArray.reverse()
    new_str =  revArray.join("")

    if (parseInt(new_str) < (Math.pow(2, 31) * -1) || parseInt(new_str) > Math.pow(2,31) - 1) {
         new_str = 0;
    }
    if (Math.sign(x) === -1) {
    
       new_str = parseInt(new_str) * Math.sign(x);
    }


  return new_str;
  };

Upvotes: 1

Arslan Ali
Arslan Ali

Reputation: 448

I had tried this solution. It has Runtime: 84 ms, faster than 98.31% of JavaScript online submissions for Reverse Integer. on Leetcode.

var reverse = function(x) {
let minus = false;
    x < 0 ? minus=true : minus=false;
    let reverse = parseInt(x.toString().split("").reverse().join(''));
    if (reverse > Math.pow(2,31) - 1) {
        return 0;
    }
    if(minus){
      return parseInt(`-${reverse}`)
    }
    return reverse
};

Upvotes: 0

jignesh patel
jignesh patel

Reputation: 51

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;

Upvotes: 3

user3507451
user3507451

Reputation: 39

It's late but still want to give the answer.

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

    if(rev > Math.pow(2, 31)){
     return 0;
    }
     else{        
      return rev*Math.sign(x);
    }    
   }

Runtime: 88 ms, faster than 95.55% of JavaScript online submissions for Reverse Integer. Memory Usage: 40 MB, less than 88.15% of JavaScript online submissions for Reverse Integer.

Upvotes: 0

Shek
Shek

Reputation: 1613

var reverse = function(x) {
     let reversed = parseInt(Array.from(`${Math.sign(x) * x}`).reverse().join(''));
     return Math.sign(x)*(reversed > 0x7FFFFFFF?0:reversed);
    
};

Runtime: 96 ms, faster than 73.30% of JavaScript online submissions for Reverse Integer. Memory Usage: 40.4 MB, less than 38.77% of JavaScript online submissions for Reverse Integer.

Not the most optimal space and time complexity though.

Upvotes: 0

zachee
zachee

Reputation: 167

function reverse(x) {
    let strArr = x.toString().split('');
    let initialString = '';
    for (let i = strArr.length - 1; i >= 0; i--) {
        initialString += strArr[i];
    }
    if (parseInt(initialString) > Math.pow(2, 31) - 1 || parseInt(initialString) < Math.pow(-2, 31)) {
        return 0;
    } else if (x < 0) {
        return -parseInt(initialString);
    } else {
        return parseInt(initialString);
    }
}

Upvotes: 0

Ohm
Ohm

Reputation: 143

var reverse = function(x) {
    let isNegative = x < 0 ? -1 : 1    
    x = x * isNegative
    const split = `${x}`.split(``)
    if(split && split.length){
        let reversedInteger = ``
        for(let i=1;i<= split.length;i++) {
             reversedInteger = reversedInteger + split[(split.length)-i]
        }
         if (reversedInteger > Math.pow(2,31)-1) {
             return 0;
         }
        return parseInt(reversedInteger*isNegative)
    }
};

Runtime: 72 ms, faster than 82.67% of JavaScript online submissions for Reverse Integer. Memory Usage: 36 MB, less than 28.12% of JavaScript online submissions for Reverse Integer.

Upvotes: -1

Arul Benito
Arul Benito

Reputation: 129

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

Upvotes: 11

Daryl
Daryl

Reputation: 25

const reverse = x => {
    let possible = x.toString().split('').reverse();
    let temp, sign, overflow;
    if(Number.isNaN(parseInt(possible[possible.length -1]))) {
      sign = possible.pop();
    }   
    temp = parseInt(possible.join(''));
    overflow = temp > 2**31-1;
    if(sign) {
        if(!overflow) {
            return temp*-1;
        }
    } else {
        if(!overflow){
           return temp;   
        }    
    }
    return 0;
};

Upvotes: -1

trincot
trincot

Reputation: 351384

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

Upvotes: 100

venkat7668
venkat7668

Reputation: 2777

This works well

var reverse = function(x) {
        let num = Math.abs(x);
        let result = 0;
        let rem;
        while(num>0){
            rem = num % 10;
            result = result * 10 + rem;
            num = Math.floor(num/10);
        }
        if(0x7FFFFFFF < result) return 0
        if(x < 0) return result * -1;
        return result;
    };

Upvotes: -1

ethanneff
ethanneff

Reputation: 3451

Here is my solution to that question. I wouldn't recommend the split().join() method as it greatly increases time and space complexity.

// 0(n)
var reverse = function(x) {
  var reverse = 0
  var isNegative = x < 0 ? -1 : 1
  x = x * isNegative

  // capture single digits
  if (x / 10 < 1) {
    return x
  }

  // reverse
  while (x >= 1) {
    var diff = parseInt(x % 10)
    reverse = (reverse * 10) + diff
    x = x / 10
  }

  // capture greater than 32bit
  if (reverse > Math.pow(2,31)-1) {
    return 0;
  }

  // capture negative
  return reverse * isNegative
};

Upvotes: 1

Robbie Milejczak
Robbie Milejczak

Reputation: 5780

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

Upvotes: 4

Related Questions