Short and simple code in Java


  • 0
    N
    class Solution {
        public int reverse(int x) {
           
            long res=0;
            boolean is_negative=false;
            if(x<0){
                x=0-x; //Removing -ve sign for caluculation
                is_negative=true; 
            }
            while(x>0){
                res=res*10+x%10;  //extracting each digit from right and  adding to the result ie:reversing number
                x=x/10;
            }
              if(is_negative)
                res=0-res;restoring back -ve sign
                
            if(res>Integer.MAX_VALUE ||res< Integer.MIN_VALUE)  // checking for overflow
                    return 0;
            
            return (int)res;     
        }
    }
    
    

Log in to reply
 

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