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