您的位置:首页 > 其它

leetcode——Reverse Integer 反转整数数字(AC)

2014-06-06 23:09 603 查看
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

这个题比较简单,考虑特殊情况如12000,注意检查反转后数字是否会越界溢出。代码如下:

class Solution {
public:
int reverse(int x) {
bool minus = false;
short int splitNum[10];
int i = 0, j = 0;
unsigned int num, result = 0;
unsigned int MAX = 2147483647;
unsigned int MIN = 2147483648;
if(x < 0)
{
num = 0 - x;
minus = true;
}
else
{
num = x;
}
while(num != 0)
{
splitNum[i++] = num%10;
num = num/10;
}
while(splitNum[j] == 0)
j++;
while(j < i)
{
if(!minus && (MAX-splitNum[j])/10 >= result)
{
result = result*10 + splitNum[j];
j++;
}
else if(minus && (MIN-splitNum[j])/10 >= result)
{
result = result*10 + splitNum[j];
j++;
}
else
{
return 0;
}
}
return minus ? (0-result) : result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode reverse integer