LeetCode 007: Reverse Integer

来源:互联网 发布:opencv骨架提取算法 编辑:程序博客网 时间:2024/05/18 02:16

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;    }};
0 0