场景:
leetcode第七题:
7、整数反转
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
问题描述:
最开始的答案:
class Solution {
public int reverse(int x) {
long y=0;
while (x!=0){
y=y*10+x%10;
x=x/10;
}
return (int)y==y?y:0;
}
}
报错:
翻译过来为:
不兼容类型:从long到int的可能有损转换
return(int)y==y?y:0;
原因分析:
long类型的y不能作为int类型返回,必须要强转为int类型。即return那要改为:
return (int)y==y?(int)y:0;
class Solution {
public int reverse(int x) {
long y=0;
while (x!=0){
y=y*10+x%10;
x=x/10;
}
return (int)y==y?(int)y:0;
}
}
成功解决
当然,这一题也可以使用try/catch的方式来做,当这种方法灵活度更高。