【python】【leetcode】【算法题目338—Counting Bits】

一、题目描述

题目原文:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

(给出一个非负整数n,返回一个列表,其元素为从0到n的二进制表示中每一项的1的个数)

题目要求:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n)  possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

(1、在时间复杂度为O(n)内完成。2、空间复杂度也为O(n)。3、不要用内置方法。

二、题目分析

思路:

首先,我们需要知道负数是没有回文数一说的。

其次,根据提示,思路1:将整形数字转化为字符串来制作。因为回文数是关于中间位置对称的,转化后根据数组下标,来进行首尾

判等操作即可(根据奇偶分为两种情况,奇数的中位数不用进行判断,且每种情况中,要判等的首位两个

数下标和为串长lenth - 1)。

思路2:将整形数字反转后与原数字判等即可,Reverse Integer题目链接如下:

http://blog.csdn.net/u014615155/article/details/53258668

我选择的是思路1,因为要考虑到不用额外空间的问题,我觉得类型转化过程中可能会有空间的浮动变化,但应该没有思路2直接开辟

新空间对空间的需求 那么多。

三、Python代码

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        #我们要知道负数不是回文数
        if x < 0:
            return False
            
        #转化为字符串,用下标来判断
        x = str(x)
        lenth = len(x)
        
        #用&操作来判定是奇数还是偶数,注意下标的匹配问题(每一对收尾判断相同的两个数的下标和恰为lenth-1)。
        if lenth & 1 == 0:
            for i in range(0, lenth / 2):
                if x[i] != x[lenth - i - 1]:
                    return False
        else:
            for i in range(0, (lenth + 1) / 2):
                if x[i] != x[lenth - i - 1]:
                    return False
        return True

四、其他

题目链接:https://leetcode.com/problems/palindrome-number/

Runtime: 221 ms

想法不够优化,欢迎大家留言交流~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值