Difficulty
Easy
Description
/**
* 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
*
*/
Solution
Time Complexity: O(log(x))
Space Complexity: O(1)
1.
class Solution {
public int reverse(int x) {
int ret = 0;
while(x != 0) {
//检查是否溢出
if (ret > Integer.MAX_VALUE/10 || (ret == Integer.MAX_VALUE/10 && x % 10 > 7)) return 0;
if (ret < Integer.MIN_VALUE/10 || (ret == Integer.MIN_VALUE/10 && x % 10 < -8)) return 0;
ret = ret * 10 + x % 10;
x /= 10;
}
return ret;
}
}
总和用long,最后转为int,检查是否溢出
class Solution {
public int reverse(int x) {
long ret = 0;
while(x != 0) {
ret = ret * 10 + x % 10;
x /= 10;
}
//检查是否溢出
return (int) ret == ret? (int)ret : 0;
}
}