JavaScript Solution with working 32-bit int check


  • 0

    Found over on StackOverflow:

    https://stackoverflow.com/questions/19843652/32-bit-signed-integer-math-in-javascript

    Bitwise operations in JS convert the number to an integer. So, if you convert your reversed result this is a way to check. Of note, comparing numberA to numberA|0 will still result in equality. I got around it by converting them to strings to check equality.

    Here's my accepted solution with no cheating. :) It could be faster but I'm lazy today.

    var reverse = function(x) {
        var neg = false;
        if (x < 0){
            neg = true;
            x *= -1;
        }
        var result = +(x.toString().split("").map(Number).reverse().join(""));
        
        if (neg){
            result *= -1;
        }
    
        if (result.toString() != (result|0).toString()) return 0;
        return result;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.