凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 7. Reverse Integer

分类:algorithm| 发布时间:2016-06-27 23:47:00


题目

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.

题意

反转一个整形的数字

解法

这道题相当简单,假设给出的数字是 x,返回值为 ret。

int ret = 0;
while (x) {
    ret = ret * 10 + x % 10;
    x /= 10;
}

需要注意 x 为负数的情况。以及当得到的结果溢出时要返回 0。

class Solution {
public:
    int reverse(int x) {
        bool negative = false;
        if (x < 0) {
            negative = true;
            x = -x;
        }

        long ret = 0;
        while (x) {
            ret = ret * 10 + (x % 10);
            x /= 10;
        }

        if (negative) {
            ret = - ret;
        }

        if (ret > INT_MAX || ret < INT_MIN) {
            return 0;
        }

        return ret;
    }
};