Simple Solution in JavaScript


  • 0
    S
    var reverse = function(x) {
         var r = 0,
            isNegative = false;
        // If the number is negative, convert it to positive and maintain a flag
        if(x < 0) {
            x *= -1;
            isNegative = true;
        }
    
        while(x) {
            r = (r*10) + (x % 10);
    	x = Math.floor(x/10);
        }
        // Check if reversed number overflows, if yes return 0
        if((r >> 0) != r) return 0;
        // If the given number was negative, restore it's negativity
        if(isNegative) return r*-1;
        return r;
    };

Log in to reply
 

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