Counting Bits (M)

题目

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:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
Input: 2
Output: [0,1,1]

Example 2:

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

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

题意

计算整数0-num的每一个数的二进制中的1的个数。要求时间复杂度为\(O(N)\),而非\(O(kN)\)

思路

个人的做法是针对每一个整数num,它二进制中1的个数,就等于把它最高位的1去掉后得到的整数的二进制中1的个数加1,如8的二进制为1000,而去掉最高位1得到的整数为0,所以8的二进制中1的个数为0+1=1。

更巧妙的方法是对于每个整数i,i&(i-1)的结果就相当于把i最右边的1变为0,这样很容易得到count[i] = count[i&(i-1)] + 1。

代码实现

Java

去掉最高位

class Solution {
    public int[] countBits(int num) {
        int[] count = new int[num + 1];
        count[0] = 0;
        int size = 1;
        int cnt = 0;
        for (int i = 1; i <= num; i++) {
            if (cnt == size) {
                cnt = 0;
                size *= 2;
            }
            count[i] = count[i - size] + 1;
            cnt++;
        }
        return count;
    }
}

去掉最右1

class Solution {
    public int[] countBits(int num) {
        int[] count = new int[num + 1];
        count[0] = 0;
        for (int i = 1; i <= num; i++) {
            count[i] = count[i & (i - 1)] + 1;
        }
        return count;
    }
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄