Sum of numbers with exactly 2 bits set | Java 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
public class Main { static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static int findSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( countSetBits ( i ) == 2 ) sum += i ; return sum ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( findSum ( n ) ) ; } }