my java solution


  • 0
    M
    public int reverse(int x) {
    	//-2147483648  2147483647
    	if(x == Integer.MIN_VALUE) {
    		return 0;
    	}
    	boolean isPositive = true;
    	if(x < 0) {
    		isPositive = false;
    		x = -x;
    	}
    	//bit
    	long bit = (long) Math.log10(x);
    	//times : 10^bit
    	long times = 0;
    	long reverseNum = 0;
    	while(x!=0) {
    		times = (long) Math.pow(10, bit);
    		reverseNum += (x % 10) * times;
    		bit--;
    		x /= 10;
    	}
    	reverseNum = isPositive ? reverseNum : -reverseNum;
    	if(reverseNum > Integer.MAX_VALUE || reverseNum < Integer.MIN_VALUE) {
    		reverseNum = 0;
    	}
            return (int) reverseNum;
        }
    

Log in to reply
 

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