首页 > 代码库 > Reverse Integer LeetCode Java

Reverse Integer LeetCode Java

 

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

 

public class Solution {
    public int reverse(int x) {
        
        if(x==Integer.MIN_VALUE)  return 0; 
        long result = 0;
        int i = 0;
        
        int temp = (x>0)?1:0;
        x = Math.abs(x);
            
        while(x != 0){
            result *= 10;
            result +=  x%10;
            x /= 10;
            if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) return 0;
        }
        return (temp==1)?(int)result:(int)-result;
        
        
    }
}

 

Reverse Integer LeetCode Java