PALINDROME
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.
Follow up:
Coud you solve it without converting the integer to a string?
思路
回文数在操作上所需要的技巧有点类似于整数反转,比起整数反转,所需要加的控制条件为控制负数返回false,反转后不相等返回false。但是反转后的数字没有了限制位数的控制条件。但我们不需要像整数反转那样将整个数字反转过来于原数进行比较,我们只需反转它的一半,与剩下的进行比较,这样我们也不用解决溢出问题了。
1.
设置负数false
2.
数字未到一半的控制条件应为已经被反转的数小于还未进行反转的数。
那么如果这个数字的位数是奇数的话,已反转与未反转的数肯定是不相同的,只需在判断的地方加一个或者的控制条件,即i= =revh||i= =revh/10,这样只是增加了一条指令的代价。
3.
还有一种情况就是,我们要注意0这个数字,结尾为零,我们花一条指令的代价将这种情况剔除,即第一次对10除余为零但数字本身不为零。
bool isPalindrome(int x) {
int revh=0;
int i;
if(x<0)
return false;
else if(0==x%10&&0!=x)
return false;
else{
i=x;
while(i>revh){
revh=i%10+revh*10;
i/=10;
}
if(i==revh||i==revh/10)
return true;
else
return false;
}
}