您的位置:首页 > 其它

【leetcode】9. Palindrome Number

2016-05-17 14:25 99 查看
/**
* 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: