本來判斷回文串是一件很容易的事情,只需要反轉字符串後在與原字符串相比較即可。這道題目明確說明不能使用額外的空間,那麼使用將其分解連接成字符串的方法便不是可行的。只好采用數學的方式: 每次取最高位和最低位相比較,總的位數可以用一個while先處理出來,循環直至取余和除數相等。
具體見代碼:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) //special due
return false;
if(x<10)
return true;
int curMod=0;
int test=x;
while(test)
{
curMod++;
test/=10;
}
curMod--;// bit num
int left=pow(10,curMod*1.0),right=10;
while(right<=left)
{
if(x%right!=x/left)
return false;
x=x%left,x/=10;
left/=100;
}
return true;
}
};