LeetCode 7. Reverse Integer 反转整数
7. Reverse Integer
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
直接反转
需要注意的是整形的溢出问题。我这里使用结果的值大于MAX/10来判断。当然也可以使用双符号位的方法来判断溢出。同样也可以使用乘以10,再除以10,比较两个数的方法来判断溢出。或者使用 异常来捕捉溢出也可以。时间复杂度为O(n),空间复杂度为O(1)
public int reverse(int x) {
if(x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE){
return 0;
}
int s = Integer.MAX_VALUE;
int sign = 1;
if( x < 0){
sign = -1;
}
int y = Math.abs(x);
int res = 0;
while(y != 0){
if(res > Integer.MAX_VALUE/10){
return 0;
}
res = res* 10 + (y % 10);
y = y/10;
}
return res * sign;
}