整数反转
很简单的一道题目
这个题目需要注意一点就是判断反转后的数字是否会越界。
- 方法:利用
Integer.MAX_VALUE
和Integer.MIN_VALUE
找到最大最小值然后进行判断就可以了,注意一点就是是 /10.0而不是10。原因自己体会一下应该就会了解(提示,整数相除还是整数,相等的情况下就需要额外谈论了)
class Solution {
public int reverse(int x) {
int ret=0;
while(x != 0)
{
if(ret> Integer.MAX_VALUE/10.0 || ret < Integer.MIN_VALUE/10.0 ) return 0;
ret = ret * 10 + x % 10;
x /= 10;
}
return ret;
}
}