美文网首页
9. Palindrome Number

9. Palindrome Number

作者: YoungDayo | 来源:发表于2017-09-21 12:24 被阅读0次
判断整数是否为回文

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


大致意思:判断一个整数是否是回文。

常规解法:将这个整数转换成字符串,然后用两个指针一个从字符串头部,另一个从字符串尾部开始,同时向中间遍历,如果每次左右两边字符都相等,则是回文数,否则不是回文数。

class Solution {
public:
    bool isPalindrome(int x) {
        stringstream stream;
        string str;
        stream<<x;
        str=stream.str();
        int n=str.length();
        for(int i=0,j=n-1;i<j;++i,--j)
        {
            if(str[i]!=str[j])
                return false;
        }
        return true;
    }
};

其他解法:通过将整数每次做余10操作,依次得到个位、十位、百位等,然后进行累乘累加操作,将低位变成高位,将原整数通过计算反转,如果反转后的整数跟原整数相等,则证明是回文数,否则不是回文数。

class Solution {
public:
    bool isPalindrome(int x) {
        int z=0;
        int n=x;
        while(x>0)
        {
            z=10*z+x%10;
            x/=10;
        }
        return n==z;
    }
};

代码提示:需要注意负整数肯定不是回文数。其实这个方法还存在一个隐患,就是如果原整数特别大,很可能反转后的整数溢出,所以保险起见还是用long long类型变量来接收反转后的整数。虽然这个代码一次通过,可能是测试用例没有特别大的整数,故意避开整数溢出问题降低难度。

相关文章

网友评论

      本文标题:9. Palindrome Number

      本文链接:https://www.haomeiwen.com/subject/jvuzsxtx.html