java练题实践(整数反转)
//给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
//整数的范围[-2^31,2^31-1)
public class Solution {
//public static StringBuffer strb ;
public static void main(String[] args) {
int c = reverse(-2147483648);//这里最大的位数的数值是2,但是反过来的时候可能会超过2
System.out.println(c);
}
public static int reverse(int x) {
try {
StringBuffer strb = new StringBuffer();//要这样定义?
if (x > 0) {
String str = Integer.toString(x);
String[] nums = new String[str.length()];
for (int i = 0; i < nums.length; i++) {
nums[i] = str.substring(i, i + 1);
int b = Integer.parseInt(nums[i]);
strb.append(b);
}
int a = Integer.parseInt(strb.reverse().toString());
return a;
} else {
int d = 0 - x;
String str1 = Integer.toString(d);
String[] nums = new String[str1.length()];
for (int i = 0; i < nums.length; i++) {
nums[i] = str1.substring(i, i + 1);
int b = Integer.parseInt(nums[i]);
strb.append(b);
}
int a = Integer.parseInt(strb.reverse().toString());
d = 0 - a;
return d;
}
} catch (NumberFormatException e) {
System.out.println("数字超过大小");
return 0;
}
}
}
这是我看到这题的第一想法,但是实际的效果并不好,在力扣中仅仅超越15%
我看到别人的想法是通过循环来获取最后一位,大家可以试试