原题有这样的提示
“Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?”
看到有人写了一个这样的答案
int reverse(int x) {
int flag=x>0?1:-1,res=0;
x=x>0?x:-x;
while(x>0){
if((2147483647.0-x%10)/10<res)return 0;
res=res*10+x%10;
x=x/10;
}
return res*flag;
}
这一句 if((2147483647.0-x%10)/10
这一句 if((2147483647.0-x%10)/10
还有别的好方法可以判断输入的一个数是否超出int范围的方法吗?
我的做法是直接 用long型:
public int reverse(int x) {
int sign = 1;
if(x < 0){
sign = -1;
x *= -1;
}
long result = 0;
while(x != 0){
result = result * 10 + x % 10;
if(sign * result > Integer.MAX_VALUE ||
sign * result < Integer.MIN_VALUE)
return 0;
x = x / 10;
}
return (int)result * sign;
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。