整数反转
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
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.
链接:https://leetcode-cn.com/problems/reverse-integer
- 无脑判断法(注意溢出)
class Solution {
public int reverse(int x) {
int result = 0;
if (x == 0) {
return x;
}
String tmp = String.valueOf(x);
StringBuilder sb = new StringBuilder();
boolean flag = false;
if (tmp.charAt(0) == '-') {
tmp = tmp.substring(1);
flag = true;
}
tmp = sb.append(tmp).reverse().toString();
if (tmp.charAt(0) == '0') {
tmp = tmp.substring(1);
}
if (flag) {
tmp = "-" + tmp;
}
try {
result = Integer.valueOf(tmp);
} catch (Exception e) {
}
return result;
}
}