View Discussion Improve Article Save Article Like Article Write an efficient program to count the number of 1s in the binary representation of an integer. Examples : Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 13 Output : 3 Binary representation of 13 is 1101 and has 3 set bits1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is, then increment the set bit count. See the program below.
Output : 2Time Complexity: O(logn) Auxiliary Space: O(1) Recursive Approach:
Output : 2Time Complexity: O(log n) Auxiliary Space: O(1) 2. Brian Kernighan’s Algorithm: Subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including the rightmost set bit. for example : 10 in binary is 00001010 9 in binary is 00001001 8 in binary is 00001000 7 in binary is 00000111 So if we subtract a number by 1 and do it bitwise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the number of times the loop executes, we get the set bit count. The beauty of this solution is the number of times it loops is equal to the number of set bits in a given integer. 1 Initialize count: = 0 2 If integer n is not zero (a) Do bitwise & with (n-1) and assign the value back to n n: = n&(n-1) (b) Increment count by 1 (c) go to step 2 3 Else return countImplementation of Brian Kernighan’s Algorithm:
Output : 2Example for Brian Kernighan’s Algorithm: n = 9 (1001) count = 0 Since 9 > 0, subtract by 1 and do bitwise & with (9-1) n = 9&8 (1001 & 1000) n = 8 count = 1 Since 8 > 0, subtract by 1 and do bitwise & with (8-1) n = 8&7 (1000 & 0111) n = 0 count = 2 Since n = 0, return count which is 2 now.Time Complexity: O(logn) Auxiliary Space: O(1) Recursive Approach:
Output : 2Time Complexity: O(logn) Auxiliary Space: O(1) 3. Using Lookup table: We can count bits in O(1) time using the lookup table.
Time Complexity: O(1) As constant time operations are performed Auxiliary Space: O(1) As constant extra space is used We can find one use of counting set bits at Count number of bits to be flipped to convert A to B
Output : 1 44. Mapping numbers with the bit. It simply maintains a map(or array) of numbers to bits for a nibble. A Nibble contains 4 bits. So we need an array of up to 15. int num_to_bits[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; Now we just need to get nibbles of a given long/int/word etc recursively.
Output : 5Time Complexity: O(log n), because we have log(16, n) levels of recursion. 5. Checking each bit in a number: Each bit in the number is checked for whether it is set or not. The number is bitwise AND with powers of 2, so if the result is not equal to zero, we come to know that the particular bit in the position is set.
Count set bits in an integer Using Lookup Table |