概述
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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) {
int flag = 0;
if(x < 0)
{
flag = -1;
x = -x;
}
int result = 0;
int k = 1;
vector<int> figure;
while(x / 10 != 0)
{
figure.push_back(x % 10);
x /= 10;
}
figure.push_back(x);
for(int i = figure.size()-1; i >= 0; i--, k *= 10)
{
result += figure[i] * k;
}
if(flag == -1)
result = -result;
return result;
}
};
最后
以上就是勤奋飞机为你收集整理的Reverse Integer的全部内容,希望文章能够帮你解决Reverse Integer所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复