Sum of numbers with exactly 2 bits set | CPP program to find sum of numbers upto n whose 2 bits are set ; To count number of set bits ; To calculate sum of numbers ; To count sum of number whose 2 bit are set ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } int findSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( countSetBits ( i ) == 2 ) sum += i ; return sum ; } int main ( ) { int n = 10 ; cout << findSum ( n ) ; return 0 ; }