9. 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.

确定一个整数是否是回文。这样做没有额外的空间。

一些提示:

负整数可能是回文?(即-1)

如果您正在考虑将整数转换为字符串,请注意使用额外空间的限制。

你也可以尝试颠倒一个整数。但是,如果您已经解决了“反向整数”问题,则知道反转整数可能会溢出。你将如何处理这种情况?

有一个更通用的方法来解决这个问题。

(1)思想1:“回文”判断:就是要判断其是否是对称的。所以,需要将其转换成字符串,然后再判断 str[i] 是否等于 str[len-1-i],如果都等于,则是,返回true;否则不是,返回false。

注意:当这个数小于0时,不是回文,返回false。

C++:

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if(x<0)
 5             return false;
 6         string str=to_string(x);
 7         int len=str.size();
 8         for(int i=0;i<len/2;i++)
 9         {
10             if(str[i]!=str[len-i-1])
11                 return false;            
12         }
13         return true;
14     }
15 };

python:

 1 class Solution:
 2     def isPalindrome(self, x):
 3         if x<0:
 4             return False
 5         str='%d' %x
 6         size=len(str)
 7         for i in range(0,int(size/2)):
 8             if str[i]!=str[size-1-i]:
 9                 return False
10         return True
原文地址:https://www.cnblogs.com/sword-/p/8038378.html