码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Number

时间:2014-08-19 23:42:35      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   for   

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 };

 

Palindrome Number,布布扣,bubuko.com

Palindrome Number

标签:style   blog   http   color   os   io   strong   for   

原文地址:http://www.cnblogs.com/bugfly/p/3923493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!