题目
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例1
输入: 123
输出: 321
示例2
输入: -123
输出: -321
示例3
输入: 120
输出: 21
题解
思路1
溢出条件有两个:
- ans * 10 + pop > MAX_VALUE
- ans * 10 + pop < MIN_VALUE
将溢出的情况放到最后一位来判断,即:
第一种溢出条件:ans * 10 + pop > MAX_VALUE
-
当出现 ans > MAX_VALUE / 10 且 还有pop需要添加 时,则一定溢出;
-
当出现 ans == MAX_VALUE / 10 且 pop > 7 时,则一定溢出,7是2^31 - 1的个位数。
第二种溢出条件:ans * 10 + pop < MIN_VALUE
-
当出现 ans < MIN_VALUE / 10 且 还有pop需要添加 时,则一定溢出;
-
当出现 ans == MIN_VALUE / 10 且 pop < -8 时,则一定溢出,8是-2^31的个位数。
代码
public 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 = x / 10;
}
return ans;
}
}
思路2
先反转,在反算,如果不等于自身,则说明发生了溢出。
代码
class Solution {
public void reverseString(char[] s) {
int i = 0;
int j = s.length - 1;
while(i < j && i != j){
char temp = s[i];
s[i++] = s[j];
s[j--] = temp;
}
}
}