PDF版 ePub版

# Palindrome Number（回文数）

## 原文

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.

public class Solution
{
public bool IsPalindrome(int x)
{
for (int i = 0; i < x.ToString().Length / 2; i++)
{
if ((x.ToString())[i] != x.ToString()[x.ToString().Length - i - 1])
{
return false;
}
}
return true;
}
}

11506 / 11506 test cases passed.
Status: Accepted
Runtime: 244 ms
Your runtime beats 0.97% of csharp submissions.

public class Solution
{
public bool IsPalindrome(int x)
{
if (x < 0)
return false;
// 判断x的长度，比如x=232，div就等于100
int div = 1;
while (x / div >= 10)
div *= 10;
while (x != 0)
{
// 左边开始计数
int left = x / div;
// 右边开始计数
int right = x % 10;
if (left != right)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
}

11506 / 11506 test cases passed.
Status: Accepted
Runtime: 196 ms
Your runtime beats 21.36% of csharp submissions.

public class Solution
{
public bool IsPalindrome(int x)
{
if (x < 0)
return false;
else if (x == 0)
return true;
else
{
int tmp = x;
int y = 0;
while (x != 0)
{
y = y * 10 + x % 10;
x = x / 10;
}
if (y == tmp)
return true;
else
return false;
}
}
}