338. Counting Bits

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 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]



统计从 0 ~ n 每个数的二进制表示中 1 的个数

11中的两个1,可以是10中的一个1加上最右边的一个1,而10中的1可以是00加上最右边的一个1

所以res【3】 = res【2】+1
res【2】 = res【0】+1


C++:
 1 class Solution {
 2 public:
 3     vector<int> countBits(int num) {
 4         vector<int> res(num+1,0) ;
 5         for(int i = 1 ; i <= num ; i++){
 6             res[i] = res[i&(i-1)] + 1 ;
 7         }
 8         return res ;
 9     }
10 };
原文地址:https://www.cnblogs.com/mengchunchen/p/10253621.html