每天一道算法题(一):给定一个整数,判断这个数是否是回文

给定一个整数,判断这个数是否是回文。
*C/C++可以使用atoi()将字符串转换成整数

bool isPalindrome (int n)
{
if (n <0)
return false;
int temp = 1;
 //找出整数n的最高位,例如:一个整数是 123321,得到的temp = 1000000
while (n/temp >= 10) 
{
temp *=10;
}
 //判断n是否为回文
while (n != 0)
{
if (n/temp != n%10)  //拿到 n 的最高位(n/temp)和最低位(n%10)
{
return false;   //如果不相等,返回false
}
n = (n%temp)/10;   //将n的最高位和最低位删除
temp /= 100;   //temp也删除两位
}
return true;
}

猜你喜欢

转载自blog.csdn.net/weixin_40222745/article/details/79205452