This is an interesting question. It is one of the most frequently asked questions during the interview. The formal name of this question is Hamming weight.
To solve this problem, the first thought must be a one-digit judgment, which is a 1-digit counter + 1. Otherwise, skip to the next position, which is very easy for beginners of programming!
So it is easy to get such a program:
int Sum1ByBin(int num){int sum = 0;while (num){if(sum %2 ==1){sum ++;}sum/=2;}return sum;}
Or use bitwise operations:
int Sum1ByBin(int num){int sum = 0;while (num){sum += num&1;num>>1;}return sum;}
The above two pieces of code use the same algorithm, and the time complexity is the number of digits in the binary. So I can think about whether there is only an algorithm related to the number of digits in the binary 1?
You can consider finding the first 1 encountered starting from the second bit, adding 1 to the counter, clearing it, And then searching for the next 1. The method is n & (n-1). This operation does not affect the current bit height,
Completely zeroes the low position. For example! 5. 5 is 101. The first calculation is 101 & 100 = 100, and the counter is incremented by one. The second calculation is 100 & 011 = 0, and the counter is incremented by one. The loop is over!
So 5 has two ones. Awesome! Let's see how the code is implemented:
int Sum1byBin(int num){int sum = 0;while(num){num &= num-1;sum++;}return 0;}It is very simple. This is the benefit of bitwise operations. It is said that this algorithm has not brought bitwise operations to the extreme, nor has it obtained the optimal solution of this algorithm.
Please look at a piece of code to see if you can understand the functions:
int Sum1byBin(int num){num =(num&0x55555555)+((num>>1)&0x55555555);num = (num&0x33333333)+((num>>2)&0x33333333);num=(num&0x0f0f0f0f)+((num>>4)&&0x0f0f0f0f);num=(num&0x00ff00ff)+((num>>4)&&0x00ff00ff);num=(num&0x0000ffff)+((num>>4)&&0x0000ffff);return num;}Slot, this is what the tabs are playing, leading to spaces so big, don't blame me!
I think back to my first impression when I met this code for the first time. What is this? ** after analysis and understanding, this function uses bitwise operations, calculate the number of 1 in a binary table. The Sub-division idea is used to calculate the number of 1 in each pair of adjacent two bits, and then calculate that the adjacent four bits have a 1, then calculate the number of adjacent values of 8-bit, 16-bit, and 32-bit. By now, the 32-bit machine int Is 32-bit.
32-bit is enough !!!
Let's take a good look. The code here is one-click and proven! Wish the children's shoes home a pleasant journey, and wish the bachelor like me to find the goddess as soon as possible !!!