首页 » 编程之美 » 正文

[leetcode_7]Reverse Integer

刚说它题意没说明,结果这个题给了一大堆说明和注意事项T_T
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).

除了越界的问题我没考虑之外,别的问题需要注意下还是。

代码一次AC。

存到数组,倒序加回来,所以零的问题不攻自破。

代码如下:

class Solution {
public:
    int reverse(int x) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int num[100];
        int top = 0;
        while(true)
        {
            num[top++] = x%10;
            x /= 10;
            if(x == 0)
                break;
        }
        int ans = 0;
        for(int i = 0;i < top;i++)
        {
            ans += num[i]*(int)pow(10.0,top - i - 1);
        }
        return ans;
    }
};

发表评论