Java interview questions - the number of 1 in the binary form of the first n numbers

Topic: Input a non-negative number n, please calculate the number of 1 in the binary form of each number between 0 and n, and output an array. For example, the input n is 4, since the numbers of 1 in the binary form of 0, 1, 2, 3, 4 are 0, 1, 1, 2, 1 respectively, so the output array [0, 1, 1, 2, 1】

The first violent solution that many people think of is to use a for loop to get the number of 1s in the binary form of each integer i from 0 to n. So the problem is transformed into how to find the number of 1s in the binary form of an integer i.

Efficient method:  use "i & (i-1)" each time to change the rightmost 1 of the integer i to zero. The integer i is subtracted by 1, then its rightmost 1 becomes zero. If there are still zeros on his right, all the zeros on the right will become 1, and the 1 on the left will become zero. Taking the binary 1100 as an example, the result of subtracting 1 is 1011, the bitwise AND operation of 1100 and 1011 It is exactly 1000. The rightmost 1 of 1100 in binary becomes zero, and the result is exactly 1000.

public int[] countBits(int num){
    int[] result = new int[num+1];//存储第i位1的数目
    for(int i = 0; i <= num; i++){
        int j = i;
        while (j !=0){//判断所有的1是否都转变为零
            result[i]++;
            j = j & (j -1);//将最后一个一的位置变为零
        }
    }
    return result;
}

Code optimization: Analysis shows that "i & (i - 1)" changes the rightmost 1 in the binary form of i to 0, that is, the number of 1s in the binary form of the integer i is greater than that of "i & (i - 1) The number of 1 in the binary form of "is 1 more than that.

public int[] countBits(int num){
    int[] result = new int[num+1];//存储第i位1的数目
    for(int i = 0; i <= num; i++){
        result[i] = result[i & (i-1)] + 1;
    }
    return result;
}

Another method: Calculate the number of 1s in the binary form of i according to "i/2":

        If the positive integer i is an even number, then i is equivalent to the result of shifting "i/2" to the left by one bit, so the number of 1s in the binary form of the even number i and "i/2" is the same. If i is an odd number, then i is equivalent to shifting "i/2" one bit to the left and then adding one, so the number of 1s in the binary form of an odd number i is one more than "i/2".

public int[] countBits(int num){
    int[] result = new int[num+1];//存储第i位1的数目
    for(int i = 0; i <= num; i++){
        result = result[i>>1] + (i&1);
    }
    return result;
}

This code snippet uses "i>>1" to calculate "i/2", and "i & 1" to calculate "i%2".

Guess you like

Origin blog.csdn.net/lijingxiaov5/article/details/122187539