LeetCode--338. Counting Bits(计算比特数)Python
2018-01-02 18:35
417 查看
题目:
给定一个整数n,返回从0-n各个整数对应二进制数中1的个数。比如n=5,返回
解题思路:
考虑二进制数的规律。[000,001,010,011,100,101,110,111],分别对应[0,1,2,3,4,5,6,7]。从上述二进制数可以看出来,4-7的二进制数既是对0-3的二进制数的最高位从0变成1,也就是说后面的二进制数都是在之前所有二进制的最高位加一位1。
代码(Python):
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
List1 = [0]
while(len(List1)<=num):
List2 = [i+1 for i in List1]
List1 = List1+List2
return List1[:num+1]
给定一个整数n,返回从0-n各个整数对应二进制数中1的个数。比如n=5,返回
[0,1,1,2,1,2].
解题思路:
考虑二进制数的规律。[000,001,010,011,100,101,110,111],分别对应[0,1,2,3,4,5,6,7]。从上述二进制数可以看出来,4-7的二进制数既是对0-3的二进制数的最高位从0变成1,也就是说后面的二进制数都是在之前所有二进制的最高位加一位1。
代码(Python):
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
List1 = [0]
while(len(List1)<=num):
List2 = [i+1 for i in List1]
List1 = List1+List2
return List1[:num+1]
相关文章推荐
- LeetCode 338. Counting Bits(统计比特数)
- leetcode 338. Counting Bits 位计算 + 统计二进制1的数量
- 【leetcode】338. Counting Bits(C++ & Python)
- LeetCode 338. Counting Bits(计算二进制数中1的位数)
- python--leetcode338. Counting Bits
- LeetCode:338. Counting Bits(C++)
- 191. Number of 1 Bits Leetcode Python
- leetcode 338. Counting Bits
- [leetcode] 338. Counting Bits
- [LeetCode: Python]190. Reverse Bits
- LeetCode No338. Counting Bits
- 【leetcode】【Medium】【338. Counting Bits】【规律】
- LeetCode 338. Counting Bits
- 【LeetCode】338. Counting Bits
- [leetcode: Python]191.Number of 1 Bits
- LeetCode Number of 1 Bits 计算1的个数
- leetcode 338. Counting Bits
- Leetcode 338. Counting Bits
- LeetCode题目:338. Counting Bits
- [LeetCode]338. Counting Bits