给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。
示例 1:
输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:
输入:n = 5
输出:[0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
提示:
0 <= n <= 10^5
进阶:
很容易就能实现时间复杂度为 O(n log n) 的解决方案,你可以在线性时间复杂度 O(n) 内用一趟扫描解决此问题吗?
你能不使用任何内置函数解决此问题吗?(如,C++ 中的 __builtin_popcount )
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/counting-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:线性时间复杂度为O(n)的解法
设f(n)表示数字n的二进制表示中1的个数。
如果n是偶数,那么n的二进制表示中的最低位为0(有n&1=0),n右移一位之后,其二进制表示中1的个数不变,即f(n)=f(n>>1);如果n是奇数,那么n的二进制表示中的最低位为1(有n&1=1),n
右移一位,其二进制表示中1的个数少了1,f(n)=f(n>>1)+1。
综上,f(n)=f(n>>1)+(n&1);则可以使用动态规划算法:
class Solution {
public int[] countBits(int n) {
int[] ans = new int[n+1];
for(int i=1; i<=n; i++){
ans[i] = ans[i>>1]+(i&1);
}
return ans;
}
}
方法二:时间复杂度为 O(n log n)
Brian Kernighan 算法:对于任意整数 x,令 x=x & (x−1),该运算将 x 的二进制表示的最后一个 1 变成 0。因此,对 x 重复该操作,直到 x 变成 0,则操作次数即为 x 的「一比特数」。
class Solution {
public int[] countBits(int n) {
int[] ans = new int[n+1];
for(int i=1; i<=n; i++){
ans[i] = count(i);
}
return ans;
}
public int count(int n){
int num = 0;
while(n>0){
n &= n-1;
num++;
}
return num;
}
}