1.Reverse Integer
Reverse digits of an integer.
(反转整形数字)
Example:
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.(输入为32位整数,直接返回0)
思路:直接转化为字符串数组循环遍历,通过StringBuilder连接。
public class ReverseInteger {
public int reverse(int x) {
boolean flag = false;
int result = 0;
if (x < 0) {
flag = true;
x = Math.abs(x);
} else if (x == 0) {
return 0;
}
String str = String.valueOf(x);
char[] chars = str.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for (int i = str.length(); i > 0; i--) {
stringBuilder.append(chars[i - 1]);
}
try {
if (flag) {
result = -(Integer.valueOf(stringBuilder.toString()));
} else {
result = Integer.valueOf(stringBuilder.toString());
}
} catch (NumberFormatException e) {
return 0;
}
return result;
}
}
这种方法通过转化成char数字来操作x中每个数字(显然非常的low).
可以用递推算法实现,int类型上通过 %10 求最后一位数字。
public class ReverseInteger {
public int reverse(int x) {
long result = 0;
while(x != 0)
{
result = (result*10) + (x%10);
if(result > Integer.MAX_VALUE) return 0;
if(result < Integer.MIN_VALUE) return 0;
x = x/10;
}
return (int)result;
}
public static void main(String[] args) {
ReverseInteger reverseInteger = new ReverseInteger();
System.out.println(reverseInteger.reverse(123));
}
}