Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
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?
There is a more generic way of solving this problem.
每次区首尾两位进行比较,然后再去掉首尾两位循环。
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <sstream>
#include <cstring>
#include <cmath>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
{
return false;
}
//数字长度
int len = 0;
int temp = x;
while(temp != 0)
{
temp = temp / 10;
len++;
}
while(x != 0)
{
int bottom = x % 10;
int top = x / (int)pow(10, len - 1);
if (bottom != top)
{
return false;
}
x = (x % (int)pow(10, len - 1)) / 10;
len -= 2;
}
return true;
}
};
int main()
{
Solution s;
cout << s.isPalindrome(123212) << endl;
return 0;
}
本文介绍了一种不使用额外空间判断整数是否为回文数的方法。通过对比整数的首位数字并逐步移除已比较的数字实现循环判断。文章提供了一个C++示例程序,展示了如何通过这种方式高效地解决回文数的问题。
556

被折叠的 条评论
为什么被折叠?



