關(guān)于 判斷整數(shù)是不是是回文數(shù)
幾種解法:1是將整數(shù)轉(zhuǎn)化為字符情勢,但需要額外空間;2是將數(shù)字逆轉(zhuǎn)得到另外一個(gè)數(shù),判斷是不是與原數(shù)相等,但有可能溢出;
符合要求的方法是從數(shù)的兩端向中間推動判斷;如相等則棄掉首尾數(shù)字;
bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) {
div *= 10; } //算數(shù)的量級
while (x != 0) {
int l = x / div; //取首數(shù)字
int r = x % 10; //取尾數(shù)字
if (l != r) return false;
x = (x % div) / 10; //去除首尾
div /= 100;
}
return true;
}