【LEET-CODE】9. Palindrome Number

来源:互联网 发布:投资返利网站源码 编辑:程序博客网 时间:2024/06/01 09:46

Question:

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.

思路:

判断一个整数是否是回文数。思路不难,但是要注意 ^ 在C++中不是乘方运算, 应该用pow(10,x)来实现10^x。

Code:

class Solution {  public:      bool isPalindrome(int x) {          if (x < 0)              return false;                        if (x < 10)              return true;                        int digits = 0;          int t = x;          int d = 0;          while(t != 0) t /= 10, ++d;                    int left = pow(10, d - 1);          int right = 1;          while( left >= right)          {              if (x / left % 10 != x / right % 10)                  return false;                            left /= 10;              right *= 10;          }          return true;      }  };  


0 0
原创粉丝点击