【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;
    }
};
 
 
 
 
posted @ 2014-06-13 13:06  z陵  阅读(371)  评论(0编辑  收藏  举报