力扣338. 比特位计数

 1. 遍历1-num的所有二进制

2. 使用布赖恩·克尼根算法,xor & (xor - 1)即可移除xor最右边的那个1,省去了移除0的过程,减少了迭代次数,直接删除最右边的1

 1 class Solution {
 2     public int[] countBits(int num) {
 3         // 遍历1-num的所有二进制
 4         int[] res = new int [num + 1];
 5         Arrays.fill(res, 0);
 6         for(int i = 0; i <= num; i++){
 7             res[i] = 0;
 8             int temp = i;
 9             while(temp != 0){
10                 res[i]++;
11                 temp = temp & (temp - 1);   // 使用布赖恩·克尼根算法,xor & (xor - 1)即可移除xor最右边的那个1,省去了移除0的过程,减少了迭代次数,直接删除最右边的1
12             }
13         }
14         return res;
15 
16     }
17 }

算法复杂度为:

时间复杂度为O(n*k), 对于每个数x, k表示x中1的个数

空间复杂度:O(n)。 我们需要 O(n) 的空间来存储计数结果。如果排除这一点,就只需要常数空间。

猜你喜欢

转载自www.cnblogs.com/hi3254014978/p/12939972.html