Description:
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?
描述:
确定给定数字是否是回文数字。如果某个数字顺序读和逆序读时一致,则该数字为回文数字。
例子1:
输入:121 输出:true
例子2:
输入:-121 输出:否 解释:正序读表示-121,逆序读表示121-,两者不相同
例子3:
输入:10 输出:否
方法一:转换为字符串,并判断字符串是否为回文字符串。
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
string s;
while(x) {
int n = x % 10;
s.push_back(n + '0');
x = x / 10;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s[i] != s[j])
return false;
i++;
j--;
}
return true;
}
};
时间复杂度为O(max(lg(x), n),空间复杂度为O(lg(x))。
方法二: 折半反转。
对于一个数字,可以首先将该数字反转,然后比较两个数字是否相等。
实现方法可以参考回文数字,思路如下:
pop = x % 10
temp = temp * 10 + pop
x = x / 10。
但是,这样的方法需要考虑溢出问题。例如,对于INT_MAX(2147483647),其反转后的数字会溢出。
一种简化方法是只反转数字的一半。例如,对于数字1221,只反转后一半1221,反转后为12,未反转部分也为12,二者相等,表示数字1221为回文数字。
接着,我们需要考虑如何判断循环的结束。按照上述思路,temp = temp * 10 + pop,对于偶数位数字,如1221,当运算后temp * 10 大于x时(此时temp*10为120,x为12)循环结束。对于奇数位数字,如12321,当运算后temp大于x时(此时temp为123,x为12)循环结束。
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
if(x < 10) return true;
if(x % 10 == 0) return false;
int temp = 0;
while(temp < x) {
int n = x % 10;
temp = temp * 10 + n;
x = x / 10;
if(temp > x) {
if(temp / 10 == x)
return true;
else
return false;
}
if(temp * 10 > x) {
if(temp == x)
return true;
else
return false;
}
}
return false;
}
};
时间复杂度为O(lg(x)),空间复杂度为O(1)。