Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

 

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
主要是获取整数的长度,然后两个指针分别从整数的两边进行比较,然后往中心移动,如果不相等就返回false,全部相等返回true
class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        int n = len_of_integer(x);
        int left = n;
        int right = 1;
        while (left > right) {
            int l_num = get_num_of_position(x, left);
            int r_num = get_num_of_position(x, right);
            if (l_num == r_num) {
                left--;
                right++;
            } else {
                return false;
            }
        }
        return true;
    }
    int len_of_integer(int x) {
        int n = 0;
        while (x) {
            x = x / 10;
            n++;
        }
        return n;
    }

    int get_num_of_position(int x, int p) {
        int m = pow(10, p);
        int n = pow(10, p - 1);
        int y = x % m;
        return y / n;
    }
};

 

posted on 2016-01-03 20:53  walkwalkwalk  阅读(172)  评论(0编辑  收藏  举报

导航