题目:
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
提示:
此题的关键是要解决溢出这一特殊情况,有两种解决方法:
- 声明一个long long型变量,返回之前检查其大小是否溢出;
- 在每一次循环过程中对数值检测。
代码:
方法1:
class Solution { public: int reverse(int x) { long long int result = 0; while (x) { result = 10 * result + x % 10; x = x / 10; } return result > std::numeric_limits<int>::max() || result < std::numeric_limits<int>::min() ? 0 : result; } };
方法2:
class Solution { public: int reverse(int x) { if (x == INT_MIN) return 0; if (x < 0) return -reverse(-x); int rx = 0; // store reversed integer while (x != 0) { // check overflow if (rx > INT_MAX / 10 || 10 * rx > INT_MAX - x % 10) return 0; rx = rx * 10 + x % 10; x = x / 10; } return rx; } };