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,并返回一个保存个数的向量。
这题我做出了两种解法。
解法一:
这种方法比较简单。直接判断数字的每个位是否为1。要实现只需遍历每个数字,然后与2的整数次幂作与(&)运算技能判断该位是否为1。算法时间复杂度为O(N)。
<span style="font-size:12px;">class Solution {</span>
public:
vector<int> countBits(int num) {
vector<int> ans ;
for (int i=0; i<=num; i++) {
int cnt = 0 ;
int k = 1 ;
for (int j=0; j<=30; j++) {
if (i & k) cnt++ ;
k *= 2 ;
}
ans.push_back(cnt) ;
}
return ans;
}
};
解法二:
第二种相对第一种解法比较快,但算法原理也稍微复杂。通过对一些数字的二进制数进行观察,我们很容易就会发现一个规律:
一个数的1的位数等于它与小于等于它的最大的2的整数次幂数的差的1的位数加上1。举个简单的例子,15(1111)的1的位数正好比7(0111)的位数多1。而15-7=8正好是小于等于15的最大的2的整数次幂的数。
因此,我们可以用动态规划的思想做这道题。
ans[i] = ans[i-temp] + 1 ;
而ans[0] = 0 ; temp 为小于等于i的最大的2的整数次幂数。
代码如下:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans ;
ans.push_back(0) ;
int temp = 1 ;
for (int i=1; i<=num; i++) {
ans.push_back( ans[i-temp] + 1 ) ;
if (i == temp*2-1) temp *= 2 ;
}
return ans ;
}
};