7. Reverse Integer

7. Reverse 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.

Analysis:
一定要注意整数反转后溢出的情况。
跟190. Reverse Bits 这道题类似。

Source Code(C++):

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int reverse(int x) {
        const int max_int = 0x7fffffff;
        const int min_int = 0x80000000;
        long long x_reverse=0;
        while(x != 0)
        {
            x_reverse = x_reverse*10 + x%10;
            if (x_reverse>max_int || x_reverse<min_int) {
                return 0;
            }
            x /= 10;
        }
        return x_reverse;
    }
};

int main() {
    Solution sol;
    cout << sol.reverse(-123);
    return 0;
}

你可能感兴趣的:(7. Reverse Integer)