leetcode Palindrome Number (判断整数是否为回文)

来源:互联网 发布:mac尘埃3汉化 编辑:程序博客网 时间:2024/06/05 06:31

题目:
Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

这题比较简单, 题目要求判断一个整数是不是回文, 回文的意思就是倒过来和原来一样, 比如1234321. 题目要求不能使用额外空间。
只要把整数翻转然后和原来的数比较就可以了, 负数不是回文(为什么啊)

code:

class Solution{public:     bool isPalindrome(int x)     {         if(x<0)            return false;         long long res = 0;         int tmp = x;         while( tmp!=0 )         {             res = res*10 + tmp%10;             tmp = tmp/10;         }         if( res>INT_MAX )             return false;         return  res==x;     }};
  1. 不用考虑溢出, 直接从前后两端开始比较每个数字, 判断是否相等
    code
class Solution {  //compare both the left most and the right most digit,   //if not equal return false  public:      bool isPalindrome(int x)     {        if(x<0)        return false;      int len=1;      while( x/len >= 10)      {           len=len*10;      }      while(x!=0)      {       int left = x/len;       int right = x%10;       if( left!=right )          return false;       x = (x%len)/10;       len=len/100;      }      return true;     }  };
0 0