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:
For num =
5
you should return[0,1,1,2,1,2]
.
题目内容:
题目给出一个非负整数num,让我们分别求出[0, num]这个区间内的所有整数对应二进制数当中1的个数。例如[0, 5]区间中所有整数的二进制中1的个数如下表:
十进制 | 二进制 | ‘1’的个数 |
---|---|---|
0 | 0 | 0 |
1 | 1 | 1 |
2 | 10 | 1 |
3 | 11 | 2 |
4 | 100 | 1 |
5 | 101 | 2 |
解题思路:
这一道题我们可以遍历[0, num]中的所有整数,转换成二进制,再计算当中’1’的个数,这样的复杂度是O(n∗sizeof(int)),虽然说sizeof(int)一般情况下是等于32的,那么复杂度其实也可以表示为O(n)。但是我们能否找到一种方法只需要遍历一次区间,不用遍历二进制的每一位就可以得到结果呢?
这道题在LeetCode中是属于动态规划(Dynamic Programming)的题目,所以我们可以尝试从动态规划的角度出发。假如用result[i]表示非负整数i的二进制表示中’1’的个数,那么result[i]应该怎样通过result[0]…result[i - 1]算出来。我们知道,在十进制中,一个数字除以2(整数除法),相当于将其二进制数往右移一位,例如
所以,我们是否能够通过result[i / 2]来计算出result[i]。答案是可以的,假如i的二进制位数为j,那么通过result[i / 2]我们可以得到前面j−1位中’1’的个数,然后再通过i判断剩下那一位是否1,就可以计算出result[i]。
所以这个动态规划中,result[0]=0,状态迁移方程为:
代码:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> countBits(int num) {
vector<int> result(num + 1);
result[0] = 0;
for (int i = 1; i <= num; i++) {
result[i] = result[i / 2] + i % 2;
}
return result;
}
};