[leetcode] 9. Palindrome Number 解题报告

题目链接:https://leetcode.com/problems/palindrome-number/

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

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.


思路:使用数学的方法,通过除余和初的操作来取得最高位和最低位的数字,通过是否相等来判断是否是回文数字

代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) 
            return false;
        int num = 1;
        while(x/num >= 10)
            num *= 10;
        while(x > 0)
        {
            int high = x/num;
            int low = x%10;
            if(high != low)
                return false;
            x = (x%num)/10;
            num /= 100;
        }
        return true;
    }
};
参考:http://www.cnblogs.com/grandyang/p/4125510.html

你可能感兴趣的:(LeetCode,算法,回文数,palindrome)