Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Code:
/**
*
*/
/**
* @author MohnSnow
* @time 2015年6月2日 上午11:41:19
*
*/
public class LeetCode7 {
/**
* @param argsmengdx
* -fnst
*/
//边界条件的考虑,
public static int reverse(int x) {
int result = 0;
int flag = x < 0 ? -1 : 1;//三目运算符去代替if else的判断
x = x * flag;
while (x > 0) {
if (Integer.MAX_VALUE / 10 < result) {//判断溢出:result * 10;
return 0;
}
if (Integer.MAX_VALUE - result * 10 < (x % 10)) {//判断溢出:result,其实就是对下面式子 的溢出判断
return 0;
}
result = (x % 10) + result * 10;
x /= 10;
}
return result * flag;
}
public static void main(String[] args) {
int a = 1534236469;
System.out.println(a);
System.out.println(reverse(a));
}
}