Solution in javaScript


  • 0
    S
    /**
     * @param {number} x
     * @return {number}
     */
    var reverse = function(x) {
        var num = x.toString(); 
        var len = num.length-1;
        var rev = "";
        var i=len, result;
        
       // find the location of the first non-zero number from the end 
        while(num.charAt(i) == "0"){
            i--;
        }
    
        if(i==-1){  // corner case: the number was 0
            result =0;
        } else {
            // get the number after removing the zero's from the end and reverse the string
            rev = num.slice(0,i+1).split("").reverse().join("");   
            if(rev.charAt(rev.length-1)=="-"){ // check if the number is negative
                result = 0 - parseInt(rev);  // this adds a negative sign
            } else {
                result = parseInt(rev);
            }
    
            // The 32-bit int data type can hold integer values in the range of −2,147,483,648 to 2,147,483,647. 
           // if the result is outside the 32 bit range return 0
            if ((result < -2147483648) ||(result > 2147483648)){ 
                result = 0; 
            }        
        }   
        return result;
    };
    

Log in to reply
 

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