/**
* Determine whether an integer is a palindrome. Do this without extra space.
*/
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <limits.h>
using namespace std;
#define NUMBER(x, n) ((n) == 1 ? (x)%10 : (x) / (int)pow(10, (n-1)) % 10)
bool isPalindrome(int x)
{
if (x < 0 || x > INT_MAX)
{
return false;
}
int len = 0;
int tmp = x;
while (tmp != 0)
{
tmp = tmp / 10;
len++;
}
int high = 0, low = 0;
int h, l;
for (int i = 1; i <= len; i++)
{
low = i;
high = len - i + 1;
l = NUMBER(x, high);
h = NUMBER(x, low);
if (l != h)
return false;
}
return true;
}
//leetcode比较优秀的答案
bool isPalindrome(int x) {
if (x<0 || (x != 0 && x % 10 == 0)) return false;
int sum = 0;
while (x>sum)
{
sum = sum * 10 + x % 10;
x = x / 10;
}
return (x == sum) || (x == sum / 10);
}
int main()
{
int num = 3445543;
cout << isPalindrome(num);
system("pause");
return 0;
}
【leetcode】9. Palindrome Number
最新推荐文章于 2020-04-04 08:08:20 发布