Palindrome Number

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.

 

方法一:不断让首位和个位进行比较,如果不相等,则不是,直到只剩下一位数,那么这个数就是回数。代码如下:

 

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if( x < 0 ) return false;   //若为负数,则返回false
 5         int cnt = 0;
 6         int num = x;
 7         while( num ) {  //求出整数的位数
 8             num /= 10;
 9             ++cnt;
10         }
11         while( cnt > 1 ) {
12             int base = pow(10, cnt-1);  //为求最高位做准备
13             if( x / base != x % 10 ) return false;  //如果首位和个位不等
14             x = (x % base) / 10;    //更新相应的值
15             cnt -= 2;
16         }
17         return true;
18     }
19 };

 

方法二:不断取末尾的数,加至新的数中,即num = num * 10 + a,如果最后num与x相等,那么就是回数,代码如下:

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if( x < 0 ) return false;   //若为负数,则不是回文
 5         int num = 0;    //新数
 6         int tx = x;
 7         while( tx ) {
 8             num = num * 10 + tx % 10;   //不断加入x的个位数
 9             tx /= 10;
10         }
11         return num == x;    //若相等,则说明是回数
12     }
13 };

 

posted on 2014-08-19 22:54  bug睡的略爽  阅读(116)  评论(0编辑  收藏  举报

导航