题目描述:
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?
第一想法是把数字转为字符串,但题目要求不这么做。
然后想到反转数字。
//x为要判断的数字 (不用考虑负数,因为负数肯定不是回文数)
// int temp = x;
int revNum = 0;
do{
revNum = revNum * 10 + num % 10;
x = x / 10;
}while(x != 0);
判断revNum 和 x(temp)是否相等就可以了。
但在反转时, revNum = revNum * 10 + num % 10 会导致溢出。
当时想到溢出问题,但不知道怎么解决。看题解后才明白,只需将数字的一半(数字长度的一半)进行反转。
例如 1221,只需将后半部分21进行反转。反转后为12,与前半部分相同,所以是回文数。
但是要怎么才知道反转数字的位数达到一半?
实际上,当x < revNum时,说明已经对半或过一半了。(想了一会儿才想明白为什么)
int revNum = 0;
while(x > revNum) {
revNum = revNum * 10 + x % 10;
x /= 10;
}
最后当数字长度为偶数时,只用判断x 和 revNum是否相等。
当长度为奇数时,原始数字最中间位的数字位于revNum的最低位上,把revNum / 10和 x进行判断。
例如, 12321,while执行完后 revNum = 123, x = 12,除掉末位3就行了。