11.力扣c++刷题-->判断是否为回文数

#include
#include
#include
using namespace std;

class Solution {
public:
    bool isPalindrome(int x)
    {
        if (x <= 10) return false;
        vector<int> a;
        vector<int> b;
        while (1)
        {
            a.push_back(x % 10);
            x = x / 10;
            if (x != 0)
            {
                continue;
            }
            else
            {
                break;
            }
        }
        for (auto& it : a)
        {
            cout << it << endl;
        }
     
        for (int i = a.size() - 1;i >= 0; i--)
        {
            b.push_back(a[i]);  
        }

        for (int i = 0; i < a.size(); i++)
        {
            if (b[i] != a[i])
            {
                return false;
            }
        }
        return true;

    }
};
int main()
{
    Solution a;
    cout <<"a.isPalindrome : " << a.isPalindrome(1121) << endl;

    return 0;
}

优化代码

#include
#include
#include
using namespace std;

class Solution {
public:
    bool isPalindrome(int x)
    {
        if (x <= 10) return false;
        
        int origin = x;
        int reverse = 0;

        while (x > 0)
        {
            reverse = reverse * 10 + x % 10;
            x = x / 10;
        }

        return reverse == origin;
       
    }
};
int main()
{
    Solution a;
    cout <<"a.isPalindrome : " << a.isPalindrome(121) << endl;

    return 0;
}

你可能感兴趣的:(c++力扣刷题,c++,leetcode,算法)