判斷一個整數(shù)是否是回文數(shù)?;匚臄?shù)是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數(shù)。
示例 1:
輸入: 121
輸出: true
示例 2:
輸入: -121
輸出: false
解釋: 從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個回文數(shù)。
示例 3:
輸入: 10
輸出: false
解釋: 從右向左讀, 為 01 。因此它不是一個回文數(shù)。
C
bool isPalindrome(int x){
if(x<0)
return false;//負(fù)數(shù)肯定不符合要求,直接false
int len=1;
while(x/len>=10){
len=len*10;//x=12321,len=10000,計算出位數(shù)
}
while(x){
int left=x/len;
int right=x%10;
if(left!=right){
return false;
}
x=x%len;//去除掉最高一位
x=x/10;//去除最低一位
len=len/100;//更新x的位數(shù)
}
return true;
}
C++
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
int len = 1;
while(x / len >= 10) {
len = len * 10;
}
while(x) {
int left = x / len;
int right = x % 10;
if(left != right) {
return false;
}
x = x % len;
x = x / 10;
len = len / 100;
}
return true;
}
};
C++_偷懶版
class Solution {
public:
bool isPalindrome(int x) {
string str=std::to_string(x);
for(int i=0,j=str.length()-1;i<j;i++,j--){
if(str[j]!=str[i])
return false;
}
return true;
}
};