
代码:(java版)
public class Solution {
// 反转
public static int reverse(int x) {
// int aa = (int)Math.pow(2, 31) - 1; // 2147483646
// int bb = -(int)Math.pow(2, 31); // -2147483647
int res = 0;
while (x != 0) {
int last = x % 10; // 每次取末尾数字,取余取出末尾的数字
// 判断反转后的整数是否在规定范围内
if (res > 214748364 || (res == 214748364 && last > 6)) {
return 0;
}
// 判断反转后的整数是否在规定范围内
if (res < -214748364 || (res == 214748364 && last < -7)) {
return 0;
}
res = res * 10 + last; // 每次反转后整数
x /= 10; // 消掉一个末尾的数
}
return res; // 返回反转后的数
}
public static void main(String[] args) {
int before = 123000;
int after = reverse(before);
System.out.println("before:" + before);
System.out.println("after:" + after);
}
}
这段代码展示了一个Java方法,用于反转一个整数。程序在反转过程中检查结果是否超出32位有符号整数的范围(-2^31到2^31-1),如果超出则返回0。在main方法中,给出了一个示例,反转前的整数123000被反转并打印出结果。
909

被折叠的 条评论
为什么被折叠?



