leetcode-9-palindrome 顺序表

问题

题目:[leetcode-9]

思路

回文的思路,但是关键是不许借助额外空间。

代码

其实这么做,不符合要求。但是也过了。

class Solution {
public:
    bool isPalindrome(int x) {
        std::stringstream ss;
        ss << x;
        std::string ret;
        ss >> ret;

        return std::equal( ret.begin(), ret.end(), ret.rbegin() );
    }
};

代码1

本次的做法由于引入的额外变量是常数,所以并不影响。思路就是常规的解析。对于一个数字1234.分别从最高位和最低位进行解析。

  • 计算数字位数
  • 解析最高位和最低位
    • 最高位:left = x / base_left % 10
    • 最低位:right = x / base_right % 10
  • 更新基数
    • base_left /= 10
    • base-right *= 10

比如1234,开始base_left = 1000, base_right = 1.left = 1, right 4.然后更新两侧的基数,base_left = 100, base_right = 10; left = 2, right = 3. 一次类推即可

/*
不让借助额外空间,那只能从高位和低位依次去比。
*/

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
            return false;
        else if( x < 10) return true;
        else
        {
            // 首先获得数字位数
            int tmp = x;
            int n = 0;
            while(tmp)
            {
                n++;
                tmp /= 10;
            }

            // 解析最高位和最低位
            int base_left = my_pow( 10, n-1 );
            int base_right = 1;

            for( int cnt = 0; cnt < n/2; ++cnt, base_left /= 10, base_right *= 10 )
            {
                int left = x / base_left % 10;
                int right = x / base_right % 10;
                if( left != right )
                    return false;
            }
            return true;
        }
    }
private:
    int my_pow( int a, int b )
    {
        int ret = 1;
        for( int i = 0; i < b; ++i )
        {
            ret *= a;
        }
        return ret;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值