您的位置:首页 > 其它

[LeetCode]69. Recerse Integer旋转整数

2015-11-09 14:52 357 查看
原文链接:https://www.geek-share.com/detail/2658051921.html

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?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

 

Subscribe to see which companies asked this question

  解法1:使用to_string、std::reverse、stoll库函数。注意到旋转后可能溢出,因此设置临时变量时应该为long long,然后判断并处理。
class Solution {
public:
int reverse(int x) {
string s = to_string(x);
if (s[0] == '-')
std::reverse(s.begin() + 1, s.end());
else
std::reverse(s.begin(), s.end());
long long n = stoll(s);
if (n > INT_MAX || n < INT_MIN) return 0;
return n;
}
};

 

解法2:先判断输入的正负,然后对绝对值处理,每次取末位相加,最后判断是否溢出。

class Solution {
public:
int reverse(int x) {
long long res = 0;
bool isNegative = false;
if (x < 0) {
x = -x;
isNegative = true;
}
while (x > 0) {
res *= 10;
res += x % 10;
x /= 10;
}
if (res > INT_MAX) return 0;
return isNegative ? -res : res;
}
};

实际上不需要事先判断输入的正负,因为在取余的时候会自动包含进去,此时while循环的结束条件是x!=0。

class Solution {
public:
int reverse(int x) {
long long res = 0;
while (x != 0) {
res *= 10;
res += x % 10;
x /= 10;
}
if (res > INT_MAX || res < INT_MIN) return 0;
return res;
}
};

 

转载于:https://www.cnblogs.com/aprilcheny/p/4949933.html

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