Given a 32-bit signed integer, reverse digits of an integer.html
Input: 123
Output: 321javaexample2:
Input: -123
Output: -321gitexample3:
Input: 120
Output: 21算法
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.編程
package easy;
public class ReverseInteger {
class Solution {
public int reverse(int x) {
int result = 0;
int com = Integer.MAX_VALUE / 10;
char[] str = String.valueOf(x).toCharArray();
char[] newStr = new char[str.length - 1];
for (int i = str.length - 1; i > 0; i--) {
newStr[str.length - 1 - i] = str[i];
}
try {
if (newStr.length == 0) {
return x;
}
//若 start 溢出直接報異常
int start = Integer.valueOf(String.valueOf(newStr));
//保證了 ( start * 10 + end ) <= Integer.MAX_VALUE
if (x >= 0 && start <= com) {
int end = Integer.valueOf(String.valueOf(str[0]));
if (start < com || (start == com && end <= 7)) {
result = start * 10 + end;
}
}
if (x < 0) {
result = -start;
}
return result;
} catch (Exception e) {
//e.printStackTrace();
return 0;
}
}
}
}
複製代碼
《Teach Yourself Programming in Ten Years》app
IDEA經常使用快捷鍵&使用技巧post