Given a 32-bit signed integer, you need to invert the digits on each of the integers.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
note:
Assuming that our environment can only store 32-bit signed integers, the value range is [−231, 231 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.
Refer to the writing after the solution and comment
class Solution {
public int reverse(int x) {
int reve = 0;
int pop = 0;
while(x != 0){
pop = x % 10;
x /= 10;
if(reve > Integer.MAX_VALUE / 10||(reve == Integer.MAX_VALUE / 10&&pop > Integer.MAX_VALUE % 10)) return 0;
if(reve < Integer.MIN_VALUE / 10||(reve == Integer.MIN_VALUE / 10&&pop < Integer.MIN_VALUE % 10)) return 0;
reve = reve * 10 + pop;
}
return reve;
}
}
among them
if(reve > Integer.MAX_VALUE / 10||(reve == Integer.MAX_VALUE / 10&&pop > Integer.MAX_VALUE % 10)) return 0;
if(reve < Integer.MIN_VALUE / 10||(reve == Integer.MIN_VALUE / 10&&pop < Integer.MIN_VALUE % 10)) return 0;
The function is to judge whether there is overflow, and if it overflows, it will jump directly out of operation.
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.