[leetcode] 7. Reverse Integer

0. Lessons learned:

  0.1 How to hand overflow or underflow for int.

long long out;
assert(out > INT_MIN && out < INT_MAX)

1. Remaining work:

NULL

2. Question:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

3. Solution

Easy problem, just consider special input, such as overflow or underflow.

#include <iostream>
#include <assert.h>
using namespace std;

class Solution {
public:
    int reverse(int x)
    {
        long long out = 0;
        while(x)
        {
            out = out * 10 + x % 10;
            assert(out < INT_MAX && out > INT_MIN);
            x = x / 10;
        }
        if(x<0)
            return (int)-out;
        else
            return (int)out;
    }
};

int main()
{
    int x1 = 123;
    int x2 = -123;
    int x3 = 1000000003; // failed

    cout << INT_MAX << endl; 

    Solution s;
    cout << s.reverse(x3) << endl;

    system("pause");
    return 0;
}

 

你可能感兴趣的:(LeetCode)