Same Number Of Set Bits As N | CPP program to find numbers less than N that have same Number Of Set Bits As N ; function ; __builtin_popcount function that count set bits in n ; Iterate from n - 1 to 1 ; check if the number of set bits equals to temp increment count ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int smallerNumsWithSameSetBits ( int n ) { int temp = __builtin_popcount ( n ) ; int count = 0 ; for ( int i = n - 1 ; i > 0 ; i -- ) { if ( temp == __builtin_popcount ( i ) ) count ++ ; } return count ; } int main ( ) { int n = 4 ; cout << smallerNumsWithSameSetBits ( n ) ; return 0 ; }