9. 回文数
第一种做法:转换成字符串,然后反转一遍看是否相等
class Solution {
public:
bool isPalindrome(int x) {
//负数肯定不可以
if(x < 0) return false;
string s = to_string(x);
return s == string(s.rbegin(),s.rend());
}
};
第二种:数值方法,把原来的数值逐位拆解形成新的数
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
int y = x;
long long res = 0;
while(x)
{
res = res*10 + x%10;
x /= 10;
}
return res == y;
}
};