Count unset bits of a number | An optimized C ++ program to count unset bits in an integer . ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Count set bits in toggled number ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countUnsetBits ( int n ) { int x = n ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return __builtin_popcount ( x ^ n ) ; } int main ( ) { int n = 17 ; cout << countUnsetBits ( n ) ; return 0 ; }