7. Reverse Integer
2026/1/12小于 1 分钟约 239 字
7. Reverse Integer
难度: Medium
题目描述
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Constraints:
-231 <= x <= 231 - 1
解题思路
代码实现
解决方案
java
class Solution {
public int reverse(int x) {
if (x > Integer.MAX_VALUE || x< Integer.MIN_VALUE) {
return 0;
}
long temp =x;
boolean flag = false;
if (temp < 0) {
flag = true;
temp = Math.abs(temp);
}
StringBuilder sb = new StringBuilder(temp+"");
sb.reverse();
Long l = Long.parseLong(sb.toString());
if (l > Integer.MAX_VALUE || (flag && l < Integer.MIN_VALUE)) {
return 0;
}
if(flag){
return 0-l.intValue();
}
return l.intValue();
}
}