您的位置:首页 > 其它

【leetcode】7—reverse integer

2015-04-28 12:58 393 查看


Reverse Integer



Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321



思路:先判断正负,然后计算位数,最后通过取商和余数,进行转换。





class Solution {
public:
int reverse(int x) {
if (x>(numeric_limits<int>::max)()||x<(numeric_limits<int>::min)())
{
return 0;
}
int base=x;
bool flag;
if(x>0)
flag=true;
else
flag=false;
int count=1;
while (base=base/10)
count++;
int answer=0;
x=abs(x);
while(count>0)
{
int yushu=x%10;
x=x/10;
answer+=yushu*pow(double(10),--count);
if (answer<0)
{
return 0;
}

}

if (flag)
{
return answer;
}
else
{

return 0-answer;
}

}

};


测试时出现的问题:


1、其实也是这道题的主要考点,就是边界问题。当输入一个10位数,且末位为7,8,9....时,转换后范围溢出。


解决办法是:在编译时,发现如果溢出,则结果为一个负值,故进行了一个简单的判断,如果小于0,则出现错误,返回0.


这个办法有点取巧,后续补充较好的判断方法。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: