您的位置:首页 > 其它

[LeetCode]Palindrome Number

2015-10-08 18:37 197 查看
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.

/*
题号:
Determine whether an integer is a palindrome. Do this without extra space.
*/
#include<iostream>
using namespace std;

class Solution{
public:
bool ispalindrome(int x){
if (x < 0)
return false;
if (x == 0)
return true;

int base = 1;
while (x / base >= 10)
base *= 10;  //base为10^n,表示取出数的最高位

while (x){
int leftDigit = x / base;
int rightDigit = x % 10;
if (leftDigit != rightDigit)
return false;

x -= base * leftDigit;
x /= 10;

base /= 100;
}
return true;

}
};

int main()
{
Solution solution;
int n1 = -123321;
int n2 = 12321;
int n3 = 12341;
int n4 = 1001;

cout << solution.ispalindrome(n1) << endl;
cout << solution.ispalindrome(n2) << endl;
cout << solution.ispalindrome(n3) << endl;
cout << solution.ispalindrome(n4) << endl;

getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: