Scenes:
Leetcode question 7:
7. Integer inversion Gives
you a 32-bit signed integer x, and returns the result of inverting the digital part in x.
If the integer exceeds the 32-bit signed integer range [−231, 231 − 1] after the inversion, 0 is returned.
Assume that the environment does not allow storage of 64-bit integers (signed or unsigned).
Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-integer
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Problem Description:
The first answer:
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;
}
}
Reported an error:
translated as:
Incompatible types: possible lossy conversion from long to int
return(int)y==y? y:0;
Cause Analysis:
Long type y cannot be returned as int type, and must be forced to int type. That is, return should be changed to:
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;
}
}
Successfully resolved
Of course, this problem can also be done by try/catch, but this method is more flexible.