码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Number

时间:2016-01-03 22:16:41      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

 

Palindrome Number

标签:

原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5097134.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!