Leetcode-整数反转

#include<iostream>
using namespace std;

/*
    输入: 123
    输出: 321
    示例 2:

    输入: -123
    输出: -321
    示例 3:

    输入: 120
    输出: 21
*/
class Solution 
{
    public:
        int reverse(int x) 
        {
            long long res = 0;
            bool isPositive = true;
            if (x < 0) 
            {
                isPositive = false;
                x *= -1;
            }
            while (x > 0) 
            {
                res = res * 10 + x % 10;
                x /= 10;
            }
            if (res > INT_MAX) return 0;
            if (isPositive) return res;
            else return -res;
        }
};


int main()
{
    Solution s;
    cout<<s.reverse(-1230)<<endl;
    cout<<s.reverse(1230)<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m18706819671/article/details/80643948