题目链接:https://leetcode.com/problems/reverse-integer/description/
这道题目解答出来本身也并无难度,只是方法优劣而已。然后开始我还是写了个最笨的方法:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
System.out.println(reverse(123));
System.out.println(reverse(-123));
System.out.println(reverse(1350));
System.out.println(reverse(-2147483412));
System.out.println(reverse(102));
// System.out.println(Integer.MAX_VALUE);
// System.out.println(Integer.MIN_VALUE);
}
public static int reverse(int x) {
if (x == 0) {
return 0;
}
boolean negative = false;
if (x < 0) {
negative = true;
x = -x;
}
while (x % 10 == 0) {
x = x / 10;
}
String xStr = String.valueOf(x);
int[] temp = new int[xStr.length()];
int i;
for (i = 0; x >= 10; i++, x /= 10) {
temp[i] = x % 10;
}
temp[i] = x;
String maxIntStr = String.valueOf(Integer.MAX_VALUE);
String minIntStr = String.valueOf(Integer.MIN_VALUE);
if (temp.length > maxIntStr.length()) {
return 0;
}
if (temp.length == maxIntStr.length()) {
for (int j = 0; j < temp.length; j++) {
if (negative) {
if (temp[j] > Integer.valueOf(String.valueOf(minIntStr.charAt(j + 1)))) {
return 0;
} else if (temp[j] < Integer.valueOf(String.valueOf(minIntStr.charAt(j + 1)))) {
break;
}
} else {
if (temp[j] > Integer.valueOf(String.valueOf(maxIntStr.charAt(j)))) {
return 0;
} else if (temp[j] < Integer.valueOf(String.valueOf(maxIntStr.charAt(j)))) {
break;
}
}
}
}
int result = 0;
for (int j = 0; j < temp.length; j++) {
result += Math.pow(10, temp.length - j - 1) * temp[j];
}
if (negative) {
result = -result;
}
return result;
}
}
里面处理的复杂了,还得考虑是否溢出的问题。然后 LeetCode 官方竟然没有答案,不知道是否是因为这道题太简单了。。。
好吧,我去 google 了一下,然后看到了这位老哥的博客:http://www.cnblogs.com/grandyang/p/4125588.html。这位老哥贴了个不知道什么语言的官方答案,我一看确实精妙无比,充分利用了各项条件,然后我用 Java 重写之如下:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
System.out.println(reverse(123));
System.out.println(reverse(-123));
System.out.println(reverse(1350));
System.out.println(reverse(-2147483412));
System.out.println(reverse(102));
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
public static int reverse(int x) {
int result = 0;
while (x != 0) {
if (result > Integer.MAX_VALUE / 10 || result < Integer.MIN_VALUE / 10) {
return 0;
}
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
}
我曹,代码十行都没有,真的好牛逼啊!