[LeetCode] Reverse Integer

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

先给出代码。

class Solution {
public:
    int reverse(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int ans = 0;
        while(x)
        {
            ans = ans * 10 + x % 10;
            x = x / 10;
        }
        return ans;
    }
};

下面回答几个疑问:

1. 如果末尾有零,输出应该是什么?

当前的算法因为是累加生成最终的integer,故首位不可能为零。如果用string做交换操作则需要考虑去掉前导零。

2. 如果有溢出,如何处理?

由于给定函数的返回值是int,故如果出现溢出,无法范围实际的结果。此时可以考虑负数取最小int,正数取最大int返回。当然如果能返回string最好不过。

posted @ 2013-11-09 10:01  xchangcheng  阅读(380)  评论(0编辑  收藏  举报