题目大意: 将Integer类型的数字 反转输出
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
- 第一种方法:将数字转为string类型,通过StringBuilder函数转换。
public class ReverseInteger {
public static int reverse(int x) {
String str = String.valueOf(x);
StringBuilder reverse = new StringBuilder(str).reverse();
return Integer.valueOf(reverse.toString());
}
public static void main(String args[] ){
int reverse = ReverseInteger.reverse(123);
System.out.println(reverse);
}
}
- 第二种方法:通过原始的方法 。注意 int 类型 下标越界问题
public static int reverse(int x){
if (x >= 0 && x <= 2147483647) {
int a = x;
int b = x / 10;
int c = x % 10;
int result = c;
while (b != 0) {
if (result > 2147483647/10) {
return 0;
}
result *= 10;
c = b % 10;
b = b / 10;
if(result > 2147483647 - c)
return 0;
result += c;
}
return result;
}else if (x < 0 && x >= -2147483648){
x = Math.abs(x);
int b = x / 10;
int c = x % 10;
int result = c;
while (b != 0) {
if (result > 2147483647/10) {
return 0;
}
result *= 10;
c = b % 10;
b = b / 10;
if(result > 2147483647 - c)
return 0;
result += c;
}
return result;
}else {
return 0;
}
}