The solution in JavaScript ...


  • 0
    M

    In the Internet I found that there are only the "SAFE" integers in following:

    Number.MAX_SAFE_INTEGER // 9007199254740991 > Math.row(2, 31)
    Number.MIN_SAFE_INTEGER  // -9007199254740991 < -Math.pow(2, 31)
    

    My solution is here:

    var reverse = function(x) {
        var r = 0;
        var s = 1;
        if (x < 0) {
            s = -1;
            x = x * s;
        }
        while (x > 0) {
            var a = x % 10
            x = (x - a) / 10
            r = r * 10 + a;
            if (Math.pow(2, 31) < r || -Math.pow(2, 31) > r) return 0;
        }
        return r * s;
    };
    

  • 1
    E

    @mx0910-gmail.com Your code can be improved as such:

    /**
     * @param {number} x
     * @return {number}
     */
    var reverse = function(x) {
        var r = 0 
        while (x != 0) {
            var a = x % 10
            x = (x - a) / 10
            r = r * 10 + a
        }
        if (Math.pow(2, 31) < r || -Math.pow(2, 31) > r) return 0
        return r
    };
    

    The way you reverse the integer does not require a flag s


Log in to reply
 

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