Determine whether an integer is a palindrome. Do this without extra space.
这道题首先需要理解什么叫回文数,回文数就是一个数字从左边读跟右边读是一样的,数学上的理解是该數字左数第n位跟右数第n位一样。负数就直接false了。
也就是该题的问题就在于如何提取相应位的数字。当然网上看到有人现将整形转为字符串后再进行比较,确实这样就方便了许多。
代码如下:
bool isPalindrome(int x) {
if( x < 0)
return(false);
int n_mark = 1 ,n=1,n_right =x;
int head , tail;
/*n_mark 计算提取左边相应数的因子,n为x的位数*/
while(x/n_mark >=10)
{ n_mark *=10;
++n;
}
n /=2;
while(n-->0)
{/* 一个数除以最大阶数就是它的最大位数,如210/100 =2 */
head =x/n_mark;
tail =n_right%10;
if(head !=tail)
return(false);
x =x-n_mark*head;
n_right /=10;
n_mark /=10;
}
return(true);
}