[7] Leetcode integer reverse C ++ (defeated 99.88%)

Here Insert Picture Description
Here Insert Picture Description

/*
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
*/

#include "iostream"

using namespace std;

class Solution
{
public:
    int reverse(int x)
    {
        int res;
        double ans = 0;

        while (x != 0)
        {
            res = x % 10;
            if (ans > INT_MAX / 10 || ans < INT_MIN / 10)
            {
                return 0;
            }
            ans = ans * 10 + res;
            x = x / 10;
        }

        return ans;
    }
};

int main()
{
    int x;
    Solution so;
    cin >> x;
    cout << so.reverse(x) << endl;
    return 0;
}
Published 71 original articles · won praise 128 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44936889/article/details/104077149