338. Counting Bits
- Counting Bits python solution
题目描述
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.

解析
题目也比较容易理解,统计二进制中1的个数。如果这个数是奇数,直接将它前一个二进制数中包含1的个数加1。如果这个数是偶数,找到其//2后对应数的二进制数所包含1的个数。因为2倍对应二进制操作相当于右移1位,所包含1的个数不变。
// An highlighted block
class Solution:
def countBits(self, num: int) -> List[int]:
solution=[0]
for i in range (1,num+1):
if(i%2==0):
solution.append(solution[i//2])
else:
solution.append(solution[i-1]+1)
return solution
Reference
https://leetcode.com/problems/counting-bits/discuss/425623/O(n)-Python3-solution-beats-99.64
本博客介绍了一个高效算法,用于统计从0到指定数值范围内所有整数的二进制表示中1的总数。算法利用了数字的奇偶性特征,对于偶数直接查找其一半对应的1的数量,对于奇数则在其前一个数的基础上加1。
1175

被折叠的 条评论
为什么被折叠?



