動態規劃--統計給定nun,從0~num每個數二進位制表示時0的個數
阿新 • • 發佈:2019-02-05
1、題目:
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]
.
2、解答: 就是一個十進位制數轉換為二進位制的過程。除2取餘 f[i] = f[i/2] + i%2;
3、程式碼
C++程式碼
class Solution { public: vector<int> countBits(int num) { vector<int> f(num+1,0); for(int i=1;i<=num;i++) f[i] = f[i>>1] + (i&1); return f; } };
python程式碼
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
f = [0]*(num+1)
for i in range(1,num+1):
f[i] = f[i>>1] + (i&1)
return f