Leetcode 9 回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true
示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

解法1:

整数转化为字符串

#include <iostream>
#include <string>

using namespace std;


class Solution {
public:
    bool isPalindrome(int x)
    {
        if(x < 0)
            return false;
        bool ret = true;
        string str = to_string(x);

        for(int i=0; i<str.length(); i++)
        {
            if(str[i] != str[str.length()-1-i])
                return false;
        }
        return ret;
    }
};

int main()
{
    Solution s;
    cout << s.isPalindrome(1212156) << endl;

    return 0;
}

解法2:

数学解法,通过取整和取余操作获取整数中对应的数字进行比较

eg:1221

1221/1000 = 1

1221%10 = 1;

通过比较相等,把22取出

(1221%1000)/10 = 22

22/10 = 2

22%10=2

回文数

#include <iostream>
#include <string>

using namespace std;


class Solution {
public:
    bool isPalindrome(int x)
    {
        //负数直接返回
        if(x < 0)
            return false;
        //确定第一次的 除数
        int div = 1;
        while(x / div >= 10)
            div *= 10;
        while(x > 0)
        {
            int left = x / div;
            int right = x % 10;
            if(left != right)
                return false;
            x = (x % div) / 10;//跟新x
            div /= 100;//因为如果left == right的话 每一次去掉的首和尾,相当于缩小100倍
        }
        return true;
    }
};

int main()
{
    Solution s;
    cout << s.isPalindrome(121) << endl;

    return 0;
}

解法3:

直观上来看回文数,就感觉是将数字进行对折后看能否一一对应。

取出后半段数字进行翻转,需注意回文数的长度可能是奇数也可能是偶数

如果是偶数,那么对折过来两者长度相等

如果是奇数,那么对折过来有一个的长度需要去掉一位数

#include <iostream>
#include <string>

using namespace std;


class Solution {
public:
    bool isPalindrome(int x)
    {
        // 当 x < 0 时,x 不是回文数。
        // 如果数字的最后一位是 0,
        if(x < 0 || (x % 10 == 0 && x != 0))
            return false;

        int revertedNumber = 0;
        //循环终止条件x < revertedNumber 说明数字已经对半或者过半了
        while(x > revertedNumber)
        {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }

        // 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
        // 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
        // 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
        return x == revertedNumber || x == revertedNumber/10;

    }
};

int main()
{
    Solution s;
    cout << s.isPalindrome(121) << endl;

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值