Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
public class ReverseInteger {
public static void main(String[] args) {
System.out.println(reverse(-123));
}
public static int reverse(int x) {
int digit = 0;
int carry = 0;
while (x != 0) {
//1.得到原数的最后一位
carry = x % 10;
//2.判断一手原数是否越界
if (digit > Integer.MAX_VALUE / 10 || digit < Integer.MIN_VALUE / 10){
return 0;
}
//3.新的数乘以10再加上刚才得到的最后一位
digit = digit * 10 + carry;
//4.原数去掉最后一位
x /= 10;
}
return digit;
}
}
本文介绍了一种用于反转整数的算法实现,通过逐步解析每个数字并重组来完成反转过程。文章提供了一个Java示例程序,该程序能够处理包括负数在内的各种情况,并考虑了整数溢出的问题。
462

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



