文章目录
- Reverse Integer
- solution
- Algorithm
Reverse Integer
Easy
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.
solution
class Solution {
public int reverse(int x) {
if(x == 0 || x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE)
return 0;
int ret = 0;
int y = Math.abs(x);
while(y > 0){
int d = y % 10;
if(ret > Integer.MAX_VALUE/10 || (ret== Integer.MAX_VALUE/10 && d > 7) )
return 0;
if (ret < Integer.MIN_VALUE/10 || (ret == Integer.MIN_VALUE / 10 && d < -8))
return 0;
ret = ret * 10 + d;
y = y / 10;
}
if(x < 0)
ret = -ret;
return ret;
}
}
32bit也就是4个字节,也就是int类型的取值范围
Algorithm
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)