Leetcode 9:Palindrome Number

原题链接:Palindrome Number
  乍一看,这题挺简单,直接将 int 转化为 string 处理,几行代码完事

class Solution 
{
	public:
	    bool isPalindrome(int x) 
	    {
	        string s = to_string(x);
	        string s1 = s;
	        std::reverse(s.begin(), s.end());
	        
	        if (s == s1)
	            return true;
	        else
	            return false;
	    }
};

但是题目下方有个 follow up:Coud you solve it without converting the integer to a string?
enmmmm…陷入沉思

可通过循环,先计算数字的首位和末尾,然后去除首尾和末尾,依次循环可得结果

class Solution 
{
    public:
        bool isPalindrome(int x) 
        {
            if (x < 0)
                return false;
            else if (0 == x)
                return true;
            else
            {
                auto len = static_cast<int>(log10(x)) + 1;	// 计算数字位数
                if (1 == len)
                    return true;
                for (int i = len-1, j = 1; j <= (len+1)/2; j++)	// j 控制循环次数
                {
                    int front = x / static_cast<int>(pow(10, i));	//首位
                    int back = x % 10;	// 末尾

                    if (front != back)
                        return false;
                    // x 掐头去尾(去除首位和末尾),进行下一轮计算
                    x = (x - front * static_cast<int>(pow(10, i))) / 10;	
                    i = i - 2;
                }
                return true;
            }
        }
};

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值