Topic Link
Title Description
Gives a 32-bit signed integer, you need this integer number on each inverted.
Example 1:
输入: 123
输出: 321
复制代码
Example 2:
输入: -123
输出: -321
复制代码
Example 3:
输入: 120
输出: 21
复制代码
note:
Suppose we have an environment only stores the 32
bit signed integer, the range of its value [−231, 231 − 1]
. Please According to this hypothesis, if integer overflow after reverse it returns 0
.
Problem-solving program
Thinking
- Tags: Mathematics
- If you do not consider this question overflow problem is very simple. There are two ideas to solve the overflow problem, the first idea is to convert a string by Jia
try catch
to address the way, the second idea is to solve mathematical calculations. - Due to the lower string conversion efficiency and use more library function, so the program does not consider the problem-solving method, but to solve mathematical calculations.
- By circulating the numbers
x
of every one apart, in calculating the new value every step of determining whether or not overflow. - There are two overflow condition, a maximum value is an integer
MAX_VALUE
, and the other is an integer less than the minimumMIN_VALUE
, the current calculation result is providedans
, next topop
. - From
ans * 10 + pop > MAX_VALUE
this point of view overflow condition- When there is
ans > MAX_VALUE / 10
, and还有pop需要添加
when, it must overflow - When there is
ans == MAX_VALUE / 10
, andpop > 7
when, it must overflow,7
is2^31 - 1
in single digits
- When there is
- From
ans * 10 + pop < MIN_VALUE
this point of view overflow condition- When there is
ans < MIN_VALUE / 10
, and还有pop需要添加
when, it must overflow - When there is
ans == MAX_VALUE / 10
, andpop < -8
when, it must overflow,8
is-2^31
in single digits
- When there is
Code
class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int pop = x % 10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
return 0;
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8))
return 0;
ans = ans * 10 + pop;
x /= 10;
}
return ans;
}
}
复制代码
Painting Solutions
Background reply " algorithm " algorithm to join the group every day feel algorithm Watch the soul, please click on looking and forward
Reproduced in: https: //juejin.im/post/5d022cc05188255a57151f05