您的位置:首页 > 其它

leetcode Reverse Integer

2018-02-27 00:03 218 查看
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.题目:给定一个32位有符号整数,整数的反向数字。
note:假设我们正在处理一个只能在32位带符号整数范围内保存整数的环境。为了解决这个问题,假设当反整数溢出时,函数返回0。
32位有符号整数,即-231~231-1,就是[0x80000000]-[0x7fffffff],也就是-2147483648~2147483647,由此可见,反向数字可能会出现int越界问题,可以用一个long型值先算出来,然后查看是否越界,如果越界,返回0,否则进行输出,如果输出需要强制转换成int,具体如下: public int reverse(int x) {
int negative = 1;
if(x<0){
x = -x;
negative = -1;
}
long y = 0;
while(x%10!=0){
y=y*10+x%10;
x = x/10;
}
if(y>Integer.MAX_VALUE){
return 0;
}else{
return (int)y*negative;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: