To find the number of 1 in a binary number
Title Description: for unsigned variables with a byte of 1BYTE = 8 bits, the number of 1 in the second binary representation requires the algorithm to perform as efficiently as possible.
Problem Analysis: Can this question be converted to determine whether the last 1 digits of this number equals 1, and then gradually shift to the right, and continue to judge, until the number is zero.
Following this analysis, there are two parts that need to be done:
1) Judge whether the last one is zero;
2) if right shifts.
There are three ways to do this.
Idea one: 1) can be divided by 2 to see if the remainder equals 0/1 implementations; 2) can be divided by 2;
Idea two: 1) can be by and 0x01 bitwise with, if the result is 1 means the last one is 1, otherwise it is 0;2) can be shifted right to divide by 2;
Idea three: 1) can be achieved by V & (V-1), make full use of the adjacent number of the last bits different characteristics; 2) with the idea 2.
The code is as follows:
Idea 2
#include <iostream>typedef unsigned char BYTE; BYTE type in C + + is not, in fact, it is unsigned character type, people generally pay attention to its length, rather than the type using namespace std; int count (BYTE v) {int num = 0; while (v) {num + = v&0x01; Bitwise with V >>= 1; Right shift}return num; }int Main () {BYTE x = 255; The byte type is only 8bits, so the maximum can be 255, 0-255cout<<count (x) <<endl; Enter the number of 1 return 0; }
The annotations help to understand the byte type.
Idea 3
#include <iostream>typedef unsigned char BYTE; using namespace Std; int count (BYTE v) {int num = 0; while (v) {//num + = v&0x01;//v >>= 1; v &= (V-1); num++;} return num; }int Main () {BYTE x = 255; cout<<count (x) <<endl; return 0;}
It can be seen that V &= (V-1); This makes it easier to do so by eliminating the right-shift operation.
In terms of time complexity:
Idea 2, time complexity and V bits number, while a number of binary bits of LOGV, so O (LOGV);
Idea 3, directly related to the number of 1 in V, is O (M).
Thinking 1 and the same as the idea 2, but the practice is greater than the idea of 2, because the bit operation than division and the efficiency of the remainder of the high ~
Reference:
About Byte:
http://bbs.csdn.net/topics/310267652
Http://www.cxybl.com/html/bcyy/c/201109073136.html
The beauty of programming
Find the number of 1 in the binary number (the beauty of programming)