for unsigned integer variables of one byte (8bit), the number of 1 in the binary representation is obtained.
Solution One :
In addition to the second method , such as 10100011 divided by 2 to 01010001 more than 1. When the second result is 1 o'clock, the number of 1 in the binary will be reduced by one, for example,
01010001 divided by 2 is more than 00101000 1. When divisible by 2 o'clock, the number of 1 in the binary is constant, with the example, 00101000 divided by 2 to 00010100.
Public Static int getonenumber (int num) { int onenum=0; while (num!=0) { if (num%2==1) { onenum+ +; } num= (num/2); } return Onenum;}
Solution Two :
bitwise operation Right SHIFT, after the right to discard is the last one, when the last one is 1 is recorded and accumulated, and in addition to the second to seek congruential almost.
Judging the last one is 1 the method is to shift the binary number and 00000001 for "and" operation, the result is 1 then the last one is 1.
Public Static int getOneNumber1 (int num) { int onenum=0; while (num!=0) { onenum+=num&1; Num>>=1; } return Onenum;}
Solution Three :
reduce one's demand and law, Simplified Analysis When there is only one 1 o'clock in the binary number {For example, 00100000} How should I judge? For binary operation results of 0 o'clock is more convenient,
So we let the result of the operation be 0, such as 0010000&00011111=0, when there is only one 1 of the binary number. When 00011111&00011110=00011110! When =0,
In this case, the number of 00011111 in the binary number is reduced by one of 1.
Public Static int getOneNumber2 (int num) { int onenum=0; while (num!=0) { num&=num-1; Onenum++ ; } return Onenum;}
Solution Four :
Listing method, the 0-127 binary number corresponding to the number of 1 in the order of the existence of an array, you can use the index of the array directly to get the values in the array. This method is only suitable when the list of arrays is less than the number of times.
At this point, discard space for time.
To find the number of 1 in a binary number