LeetCode题解(9)--Palindrome Number

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

 

思想: 先计算出这个整数的逆序数,然后比较它和原来的数每位是否都相同即可。另外要注意负数没有回文数,还应该考虑overflow一定不是回文数。

 

AC代码:

 1 class Solution {

 2 public:

 3     bool isPalindrome(int x) {

 4         if(x<0)

 5             return false;

 6         int y=0,tmp=x;

 7         while(tmp!=0){

 8             y=10*y+tmp%10;

 9             tmp=tmp/10;

10         }

11         while(x!=0 || y!=0){

12             if(x%10!=y%10)

13                 return false;

14             x=x/10;

15             y=y/10;

16         }

17         return true;

18     }

19 };

 

advance:

其实可以不求出逆序数,直接比较,见讨论板的代码:

 1 class Solution {

 2 public:

 3     bool isPalindrome(long long x) {

 4         if (x < 0) return false;

 5         long long d = 10, e = 10;

 6         while (x / d) d *= 10;

 7         while (d > e)

 8         {

 9             if ((x % d) / (d / 10) != (x % e) / (e / 10))

10                 return false;

11             d /= 10;

12             e *= 10;

13         }

14         return true;

15     }

16 };

 

你可能感兴趣的:(LeetCode)