這個問題就是判斷整數是否為回文。
思路1:利用一個字符串,將int轉換為字符串,但這樣會需要使用額外的內存
思路2:經整數翻轉,然後與原來的整數比較是否相等,但這樣可能翻轉後的整數會溢出
思路3:不斷取整數的最高位和最低位(10進制下)進行比較,相等則取次高位和次低位進行比較
class Solution {
public:
bool isPalindrome(int x) {
if(x==0)
return true;
if(x<0)
return false;
int len=0;
int copyX=x;
while(copyX!=0)
{
++len;
copyX=copyX/10;
}
copyX=x;
for(int i=0;i<=len/2;++i)
{
if(copyX%10!=((int)(x/pow(10,(float)len-1-i))%10))
return false;
copyX=copyX/10;
}
return true;
}
};class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
int d=1;
while(x/d>=10) d*=10;//d為與x位數相同的整數,即10,100,1000等
while(x>0)
{
int q=x/d;
int r=x%10;
if(q!=r) return false;
x=x%d/10;//每次比較完之後,x就去點最高位和最低位
d/=100;
}
return true;
}
};