题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
程序:
class Solution {
public:
int reverse(int x) {
vector<int> v;
long long ans=0;
bool tag=true;
const int max32 = 0x7fffffff; //011111111111... 32位
const int min32 = 0x80000000; //100000000000... 32位
if(x<0)
{
tag=false;
x=0-x;
}
while(x)
{
v.push_back(x%10);
x/=10;
}
for(int i=0;i<v.size();i++)
{
ans=ans*10+v[i];
}
if(ans<min32||ans>max32)
return 0;
if(tag)
return ans;
else
return 0-ans;
}
};
点评:
重点为溢出的处理
本文介绍了一种反转整数的方法,并详细讨论了在32位整数环境下可能遇到的溢出问题及其解决方案。通过具体示例展示了如何在C++中实现这一功能。
624

被折叠的 条评论
为什么被折叠?



