題目大意: 將Integer類(lèi)型的數(shù)字 反轉(zhuǎn)輸出
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
- 第一種方法:將數(shù)字轉(zhuǎn)為string類(lèi)型,通過(guò)StringBuilder函數(shù)轉(zhuǎn)換耀怜。
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);
}
}
- 第二種方法:通過(guò)原始的方法 珠闰。注意 int 類(lèi)型 下標(biāo)越界問(wèn)題
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;
}
}