題目鏈接:https://leetcode-cn.com/problems/palindrome-number/
#include <bits/stdc++.h>
using namespace std;
/*
如果會溢出說明一定不是迴文數,大家可以思考一些
*/
class Solution
{
public:
bool isPalindrome(int x)
{
if(x < 0 || (x != 0 && x % 10 == 0)) return false;
int max = INT_MAX / 10;
int min = INT_MIN / 10;
int n = x;
int sum = 0;
while(x != 0)
{
// 如果該int值是一個十位數,那麼比到9位數的時候就直接比較得結果,不再執行加法,否則可能溢出
if(sum >= max || sum <= min)
{
if(x % 10 != n % 10) return false;
else if(sum != n / 10) return false;
return true;
}
sum = sum * 10 + x % 10;
x /= 10;
}
return sum == n;
}
};
int main()
{
Solution sol;
cout<<sol.isPalindrome(121)<<endl; //1
cout<<sol.isPalindrome(12321)<<endl; //1
cout<<sol.isPalindrome(0)<<endl; //1
cout<<sol.isPalindrome(2147483647)<<endl; //0
return 0;
}