Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
这个问题是实现整型数的逆转。实现起来很简单。但要考虑转换后溢出的情况。如1000000003 转换后应该是3000000001 ,但是3000000001已经超出了int型的表达范围,溢出了。所以添加对溢出的处理即可以AC。
public class Reverse_Integer { //java
public int reverse(int x) {
long result = 0 ;
while(x != 0){
result = result*10 + x%10;
x = x/10;
}
//deal overflow
if(result > 2147483647)
return 2147483647;
if(result < -2147483648)
return -2147483648;
return (int)result;
}
}
原文地址:http://blog.csdn.net/chenlei0630/article/details/40736005