Problem description
Enter an integer that outputs the number of 1 in the binary representation. Where negative numbers are expressed in complement.
Algorithm analysis
The subject needs to be put into place
When a positive integer n is passed in, assuming n=3, the binary is represented as 011
011&1 = 11 x 1, N shift right 1 bit
01&1 = 1 Another 1, n shifts 1 bits to the right
31-time Total shift required
Pass in a negative integer n, assuming that n =-22 binary is represented as
Original code: 10000000 00000000 00000000 00000010
Reverse code: 11111111 11111111 11111111 11111101
Complement: 11111111 11111111 11111111 11111110
Can share processing methods with positive integers
Code implementation
class solution11 { public : int NumberOf1 (int n" {int num = 32 ; int sum = 0 ; while (num--) {if (N & 1 = = 1 ) {sum + +; } n = n >> 1 ; } return sum ; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Sword means offer" number of 1 in binary (bitwise operation)