7. Reverse Integer

来源:互联网 发布:帝国cms不会自动刷新吗 编辑:程序博客网 时间:2024/04/28 02:23

题目:Reverse Integer

原题链接:https://leetcode.com/problems/reverse-integer/
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.

把一个整数的各位数字颠倒输出,注意考虑到在32位整数的情况下会溢出,此时应该输出0。

可以先设一个long long类型的ret,用来存放倒置之后的结果,如果最终结果大于INT_MAX或者小于INT_MIN,说明产生了溢出,否则按照正常结果输出。

代码如下:

class Solution {public:    int reverse(int x) {        long long ret = 0;        while(x){            ret = ret * 10 + (x % 10);            x /= 10;        }        return (ret > INT_MAX || ret < INT_MIN) ? 0 : (int)ret;    }};
0 0
原创粉丝点击