007. Reverse Integer
Difficulty: Easy
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.
思路
每次x对10取余,余数乘10累加起来。
要注意的是,返回值必须是int类型,反转后的数有溢出的可能,处理时使用范围比int大的整型类型,判断数值是否超出int的范围。
代码
[C++]
class Solution {
public:
int reverse(int x) {
long res = 0;
while (x) {
res = res * 10 + x % 10;
x /= 10;
}
cout << res;
if (res < INT_MIN || res > INT_MAX)
return 0;
return (int)res;
}
};
本文介绍了一种简单有效的整数反转算法实现方案,通过不断取余数并累加的方式完成整数的反转,并考虑了反转后的整数溢出的情况。
1550

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



