题解 | #回文数字#
回文数字
http://www.nowcoder.com/practice/35b8166c135448c5a5ba2cff8d430c32
这里采用找到头和为进行比较,首先找到和该数同级别的最小整数,该数除以他可以得到头;尾巴直接除10取余就可以了。找到的最小整数每次以100倍缩小(前后两个数)。
class Solution {
public:
/**
*
* @param x int整型
* @return bool布尔型
*/
bool isPalindrome(int x) {
// write code here
if(x<0)
return false;
if(x<10)
return true;
int mten = 1;
int times = 1;
while(x/mten >=10){
mten*=10;
times++;
}
int jingwei = (times%2==1)?1:0;
int mid = times/2 + jingwei;
while(times>mid){
int first = x/mten;
int last = x%10;
if(first == last)
{
x -= (first*mten);
mten/=100;
x/=10;
}
else
break;
times--;
}
if(times>mid)
return false;
else
return true;
}
};