回文数Palindrome

判断一个数字是不是回文数,我目前能想到两种方法。

  • 倒置, 看是否与原数相同
  • 优化版倒置,取一半 -> 倒置,看是否与另一半相同

第二种更好一些,因为有可能测试的数据越界了,会遇到麻烦。

直接上我用c++写好的代码

bool isPalindrome(int x)
{
    if(x < 0)
        return false;
    int tmp = x;
    int ret = 0;
    while(tmp){
        ret = ret * 10 + tmp % 10;
        tmp /= 10;
    }
    if(x == ret)
        return true;
    return false;
}

bool isPalindrome_half(int x){
    if(x < 0)
        return false;
    int half_reverted_num = 0;
    while(x > half_reverted_num){
        half_reverted_num = half_reverted_num * 10 + x % 10;
        x /= 10;
    }

    return x == half_reverted_num || x == half_reverted_num / 10;
}
posted @ 2017-12-22 22:11  一棵球和一枝猪  阅读(215)  评论(0编辑  收藏  举报