Javascript solution (takes care of overflow)


  • 0
    T

    Here's my javascript solution. The upper limit for 32 bit number is 2^31 since 1 bit will be used for the sign.

     * @param {number} x
     * @return {number}
     */
    var reverse = function(x) {
        var isNegative = x < 0;
        var reversedNumber = parseInt((x).toString().split('').reverse().join(''), 10);
        if (reversedNumber >= Math.pow(2, 31)) {
            return 0;
        }
    
        if (isNegative) {
            return -reversedNumber;
        }
    
        return reversedNumber;
    };```

  • 0

    It seems your function will not return -2147483648 (-Math.pow(2, 31)), which is the minimum value for signed 32-bit integers.


Log in to reply
 

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