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?
题目来源:https://leetcode.com/problems/palindrome-number/
先给出自己很一般的算法:
class Solution {
public:
bool isPalindrome(int x) {
if(x>=&&x<)
return true;
if (x< || x / == )
return false;
int countDigit = , saveX = x;
int* numArray = new int[];
bool flag = true;
while (x>=) {
numArray[countDigit] = x - x / * ;
countDigit++;
x = x / ;
}
x = saveX;
for (int i = ; i<countDigit; i++) {
if (numArray[i] != (int)(x / pow(, countDigit - i-)) ){
flag = false;
break;
}
else {
x = x - numArray[i] * pow(, countDigit - i-);
}
}
return flag;
}
};
照例,发现了一个印度小哥的代码很简短:https://leetcode.com/problems/palindrome-number/discuss/5165/An-easy-c%2B%2B-8-lines-code-(only-reversing-till-half-and-then-compare)
class Solution {
public:
bool isPalindrome(int x) {
if(x<|| (x!= &&x%==)) return false;
int sum=;
while(x>sum)
{
sum = sum*+x%;
x = x/;
}
return (x==sum)||(x==sum/);
}
};
其实从算法思想上来说,这种思想我也曾想过:把原有数字逆转,然后比较两数字是否相同。但是由于int的限制,很可能会发生正向的数字没有溢出,但是反向的数字就溢出的情况(例如:2147483647,调转过来就溢出了)。而由我上一篇文章中所说(https://www.cnblogs.com/jiading/p/10422265.html),Int溢出后会不断减去或者加上4294967296直至整数范围落在-2147483648 ~ 2147483647内,所以如果直接调转过来可能会导致整数数值的变化,从而导致比较的不正确,所以我没有采用这种办法,而是把整数先一位一位存在数组中,然后一位一位比较,但是这样涉及到比较的次数就较多,而且还使用了数组作为辅助内存。
而这位小哥的思路就很有价值:他没有把整个数翻转过来,而是只翻转了一半(利用条件:x>sum),所以出while循环时的可能性只有两种:1.x与sum同位数,但是sum>=x(原整数是偶数位情况) 2.sum比x高一位(原整数是奇数位情况)
而这也导致了最终判断条件是两个((x==sum)||(x==sum/10)
利用翻转一半的方法,就彻底规避了整数超出范围的情况,非常的机智。