LeetCode刷题记录3-求数字是否为回文

求一个数字是否为回文

[2017-11-23修改:增加字符串回文判断]

先写一个本人的笨办法,不过可以判断负数,该方法把整个数字每一位都存了下来(其实可以只存一半):

bool isPalindrome(int x)
{
    int temp = x;
    vector<int> vec;
    while (temp)
    {
        vec.push_back(temp % 10);
        temp /= 10;
    }
    std::reverse(vec.begin(), vec.end()); //从后往前比较

    //只需要比较一半即可
    for(int i = 0;  i < vec.size() / 2 + 1; ++i)
    {
        if (x % 10 != vec[i])
        {
            return false;
        }
        x /= 10;
    }
    return true;
}

接下来是LeetCode的解法:

bool IsPalindrome(int x) {

        // As discussed above, when x < 0, x is not a palindrome.
        // Also if the last digit of the number is 0, in order to be a palindrome, 
        // the first digit of the number also needs to be 0.
        // Only 0 satisfy this property.
        if(x < 0 || (x % 10 == 0 &&
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }

        // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
        // For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123, 
        // since the middle digit doesn''t matter in palidrome(it will always equal to itself), we can simply get rid of it.

        return x == revertedNumber || x == revertedNumber/10;
    }
判断回文字符串

提供一个判断回文字符串的方法:

bool isPalindrome__(const std::string& in)
{
    std::string res = std::string(in.begin(),
        std::mismatch(in.begin(), in.end(), in.rbegin()).first);
    return in == res;
}

mismatch的实际算法源码如下,返回一个pair包括2个容器迭代器的位置:

template<class InputIt1, class InputIt2>
std::pair<InputIt1, InputIt2>
    mismatch(InputIt1 first1, InputIt1 last1, InputIt2 first2)
{
    while (first1 != last1 && *first1 == *first2) {
        ++first1, ++first2;
    }
    return std::make_pair(first1, first2);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值