# 题目描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Coud you solve it without converting the integer to a string?

#include<math.h>
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
if(x>=0&&x<=9)
return true;
int weishu=0;
int temp=x;
while(temp) //先看一下数字总共有几位
{
temp=temp/10;
weishu++;
}
int jishu=0; //看一下是奇数还是偶数
jishu=weishu%2;
int mowei=1;
int shouwei=weishu+1-mowei;  //shouwei代表着要和末位对比的位置，而不是真正的首位
if(jishu)
{
while(x&&shouwei!=1){
int a=pow(10,shouwei-1);  //这个动作是为了取shouwei，先把后面的位数去了
if((x/a%10)!=(x%10))    //(x/a%10)是shouwei,(x%10)是末位
return false;
x=x/10;
shouwei-=2; //对比完一对，shouwei的位置就减2，因为前面的指针要往后移一位，最后一位抛弃，相当于移了2位
}

}else{   //偶数个位数也一样，区别就是shouwei剩一个还是0个

while(x&&shouwei!=0){
int  a=pow(10,shouwei-1);
if((x/a%10)!=(x%10))
return false;
x=x/10;
shouwei-=2;
}
}
return true;
}
};


# 总结

posted @ 2019-09-01 21:10  HaoPeng_Zhang  阅读(63)  评论(0编辑  收藏