【0031】反转整数/判断回文


Reverse Integer

反转一个整数
 
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
class Solution
{
public:
     int reverse( int x)
    {
         /*一位数的情况*/
         if(- 10 < x && x <  10)
        {
             return x;
        }

         /*记录负数情况,负数转换成正数处理*/
         bool ispositive =  true;
         if(x <  0)
        {
            ispositive =  false;
            x = -x;
        }

         long result =  0;
         while(x)
        {
            result = result *  10 + x %  10;
            x /=  10;
        }
         if(!ispositive)
        {
            result = -result;
        }
         return result;
    }
};

Palindrome Number

判断回文
首先想到,可以利用上一题,将整数反转,然后与原来的整数比较,是否相等,相等则为
Palindrome 的。可是 reverse() 会溢出。
正确的解法是,不断地取第一位和最后一位(10 进制下)进行比较,相等则取第二位和倒数第
二位,直到完成比较或者中途找到了不一致的位。
 
 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 
class Solution
{
public:
     /*每次算出对div的商,和对10的余数做比较
     *迭代的过程当中更新div
     */

     bool isPalindrome( int x)
    {
         if(x <  0)
        {
             return  false;
        }
         int div =  1;
         while(x / div >=  10)
        {
            div *=  10;
        }

         while(x >  0)
        {
             /*商*/
             int quotient = x / div;
             /*余数*/
             int remainder = x %  10;
             if(quotient != remainder)
            {
                 return  false;
            }
             /*把当前的开头位置去掉*/
            x = x % div;
             if(x >  0 && x <  10)
            {
                 return  true;
            }
             /*把当前的结尾位置去掉*/
            x /=  10;
             /*更新新的div除数-去掉了两位应该除以100*/
            div /=  100;
        }
         return  true;
    }
};
 
 
 
 

转载于:https://www.cnblogs.com/codemylife/p/3785622.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值