题解 | #回文数字#
回文数字
http://www.nowcoder.com/practice/35b8166c135448c5a5ba2cff8d430c32
class Solution {
public:
/*
*
* @param x int整型
* @return bool布尔型
*/
bool isPalindrome(int x) {
// write code here
//x为负数或者10的倍数时不是回文数字
if(x<0||(x%10==0&&x!=0)){
return false;
}
//找到x的最大位数
int digit = 1;
while(x/digit>=10){
digit*=10;
}
while(x!=0){
int left = x/digit;//取x最左边的数字
int right = x%10;//去x最右边的数字
if(left!=right){
return false;
}
x = (x%digit)/10;
//因为一次判断两位数字
//所以x要去掉一前一后两个数字,即取余和除法
digit/=100;
//x去掉了两位,故位数要减2
}
return true;
}
};