Recently, I have been reading algorithm books such as the beauty of programming. At the beginning, I started to look at the beauty of programming. I feel that it is too difficult and sometimes I am not willing to flip this book. However, after some time of practice, I also liked this book. The algorithms in this book involve many aspects, such as trees, linked lists, bitwise operations, arrays, and hash table applications.
Recently, my work has been almost busy. I have re-written the algorithm in the beauty of programming and recorded it here for future convenience.
Since the first question was written in 2.1, this question is not very difficult. First, the function declaration of this question is given:
/* 2.1 calculate the number of 1 in binary */INT dutcountof1inbin_1 (unsigned INT); int dutcountof1inbin_2 (unsigned INT );
Here we provide two very common and very good algorithm implementations. The Code has been annotated, So I directly paste the Code:
/* Method 1 */INT dutcountof1inbin_1 (unsigned int v) {/* Number of 1 in binary */int count = 0; while (v) {++ count; /* remove the rightmost 1 (Binary) */V & = (V-1) each time./* You can determine whether a number is a power of 2: v> 0 & (V-1) = 0) */} return count;}/* method 2 */INT dutcountof1inbin_2 (unsigned int V) {/* the idea of this algorithm is to add the binary 1 of each adjacent bit of a number, and finally obtain the total number of 1 */V = (V & 0x55555555) + (V> 1) & 0x55555555); V = (V & 0x33333333) + (V> 2) & 0x33333333 ); V = (V & 0x0f0f0f) + (V> 4) & 0x0f0f0f); V = (V & 0x00ff00ff) + (V> 8) & 0x00ff00ff ); V = (V & 0x0000ffff) + (V> 16) & 0x0000ffff); Return V ;}
The beauty of programming: 2.1 calculate the number of 1 in binary