【LeetCode】9. Palindrome Number

来源:互联网 发布:php bin2hex写入文件 编辑:程序博客网 时间:2024/06/06 01:53

 Description:

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

click to show spoilers.

Subscribe to see which companies asked this question.

题目分析:

判断是否是回文数,要求不使用额外的空间,则每次取头尾两个数判断它们是否相等,若相等删掉头尾的数。


Solution:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
            return false;
            
        int len = 1;
        while(x / len >= 10)
            len *= 10;
            
        while(x > 0)    {
            int left = x / len;
            int right = x % 10;
            
            if(left != right)
                return false;
            else    {
                x = (x % len) / 10;
                len /= 100;
            }
        }
        
        return true;
    }
};

原创粉丝点击