(LeetCode)Counting Bits -- 求二进制中1的个数
来源:互联网 发布:是以知其将败 编辑:程序博客网 时间:2024/05/21 16:57
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.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
Follow up:
- 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的个数求出来,然后存放到位置中。
__author__ = 'jiuzhang'# -*- coding:utf-8 -*-class Solution(object): def countBits(self, num): if num == 0: return [0] res = [0] bit = 0 tmp = num while tmp > 0: tmp /= 2 bit += 1 for i in xrange(bit - 1): t_res = [] for j in res: t_res.append(j + 1) res = res + t_res for i in res[:(num - pow(2, bit - 1)) + 1]: res.append(i + 1) return res
方法二:
利用位运算,右移,并做与运算。
__author__ = 'jiuzhang'class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ ans = [0] for x in range(1, num + 1): ans += ans[x >> 1] + (x & 1), return ans
0 0
- (LeetCode)Counting Bits -- 求二进制中1的个数
- leetcode 338. Counting Bits(C语言,二进制中1的个数)39
- 338. Counting Bits 数字的二进制中1的个数
- leetcode-338. Counting Bits 统计十进制数字的二进制表示中1的个数,列表的定义,奇偶判断
- LeetCode 338. Counting Bits(计算二进制数中1的位数)
- Counting Bits 计算二进制形式中的1的个数
- Leetcode:191. Number of 1 Bits(返回一个数字对应二进制中1的个数)
- [LeetCode] Counting Bits 计算二进制表示法中1的位数
- Number of 1 Bits(二进制中1的个数)
- Number of 1 Bits(二进制中1的个数)
- leetcode解题之191 # Number of 1 Bits Java版 (整数对应的二进制中1的个数)
- 338. Counting Bits(计算整数二进制表示中1的位数)
- Number of 1 Bits 数字二进制中1的个数
- 191. Number of 1 Bits&二进制中1的个数
- LeetCode中338Counting Bits的题解
- leetcode 338. Counting Bits 位计算 + 统计二进制1的数量
- 求二进制数中1的个数
- 求二进制数中1的个数
- Android 2D绘图基础
- 【CodeForces】699A - Launch of Collider(思维)
- Lua中的模块与module函数详解
- Springmvc + mybatis 组合框架
- Android Support Library 之 夜间模式
- (LeetCode)Counting Bits -- 求二进制中1的个数
- screen
- UVA 621-Secret Research
- 初学IOSUI基础第二天demo1,九宫格纯代码版本,有GIF,有源文件
- IOS开发 版本提醒
- win10和ubuntu双系统启动
- Weird Shader Problem On OpenGLES 3.0
- 【知识】太阳能板行业生产加工步骤(超详细)
- 专访格灵深瞳CTO赵勇:为" 计算机视觉" 赋予智慧的光芒