9. Palindrome Number

本文探讨了三种不同的方法来判断一个整数是否为回文数。第一种方法使用长整型反转数字;第二种方法改进了反转过程,适用于长整型输入;第三种方法采用逐位比较的方式,最多只需比较整数一半的位数。

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.

Normal Way

reverse the Integer with long Integer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class  Solution {
public :
     bool  isPalindrome( int  x) {
         if (x < 0)  return  false ;
         long  num = x,result = 0;
         while (num){
             result = result * 10 + num %10;
             num/=10;
         }
         if ( result == x)  return  true ;
         else
          return  false ;
     }
};

Improved Way

What if the input number is already a long integer?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  Solution {
public :
     bool  isPalindrome( int  x) {
         if (x<0)  return  false ;
         if (x<10)  return  true ;
         if (x%10==0)  return  false ;
        
         //actual logic
         int  v=x%10;
         x=x/10;
         while (x-v>0) //x is getting smaller every step,
         {
                 v=v*10+x%10;
                 x/=10;
         }
         if (v>x){v/=10;}
         return  v==x? true : false ;
     }
};

比如 
奇数长度:1234321
每次通过除以10和对10取余来保存下前半部分x和后半部分v,比如 x = 123432, v=1;
直到x=123,v=1234的时候,循环结束,再通过 v/10 == x,来判断数是不是回环的。
偶数长度:则直接比较 v==x 

Genetic Way

compare the first and last number of the input x. 
Maximum comparing time will be half of the length of x
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class  Solution {
public :
     bool  isPalindrome( int  x) {
         if  (x < 0)  return  false ;
         int  d = 1;  // divisor
         while  (x / d >= 10) d *= 10;  // 计算出是多少位数
         while  (x > 0) {
             int  q = x / d;  // quotient
             int  r = x % 10;  // remainder
             if  (q != r)  return  false ;
             x = x % d / 10;
             d /= 100;
         }
         return  true ;
     }
};





转载于:https://www.cnblogs.com/zhxshseu/p/27ea3ddf3ceda4bbd5c090b514b28c13.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值