判断是否是回文数字

前言

什么是回文?
回文就是正着读、反着读都一样的字符串,例如:“心连心”、“abccba”、“bcdcb”、“123321” 这些都是回文。

要求

判断一个数字是否是回文数字

做法

判断数字的每一位是否对称

代码如下

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
43
44
45
46
47
48
49
#include <iostream>
#include <math.h>
using namespace std;
class Solution {
public:
/**
*计算数字的位数
**/
int wei(int x){
    int count = 0;
    while (x>0) {
        x = x/10;
        count++;
    }
    return count;
}

/**
*    判断
**/
bool isPalindrome(int x) {
    if (x<0) {
        return false;
    }
    if (x>=0&&x<10) {
        return true;
    }else{
        int n = wei(x);
        int t = (int)pow(10,n-1);
        int tmp = x;
        int half = n/2;
        for(int i=0;i<half;i++){
            if (x/t%10==tmp%10) {
                t = t/10;
                tmp = tmp/10;
            }else{
                return false;
            }
        }
        return true;
    }
}
};

int main(int argc, const char * argv[]) {
Solution* s =  new Solution();
cout<<s->isPalindrome(1221)<<endl;
return 0;
}

Comments