问题描述
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
判断一个数是否为回文数。
注意:
- 负数不是回文数
- 整型溢出问题
问题分析
将整数从低位到高位放入一个数组中,然后对整个数组进行首尾是否相等判断,如果不相等,则不是回文数。
代码
class Solution {
public:
bool isPalindrome(int x) {
// 当x为负数时,返回false
if (x < 0) return false;
// 当x为个位数时,返回true
if (x / 10 == 0) return true;
// 记录每一位数字,以个十百千万……顺序
int s[11];
// 数字位数
int counter = 0;
int tmp = x;
while (tmp) {
// 数字转字符
s[counter] = tmp % 10;
counter++;
tmp /= 10;
}
// 进行回文数判断
for (int i = 0; i <= counter/2; i++) {
if (s[i] != s[counter - i -1]) {
return false;
}
}
return true;
}
};