Sum of numbers with exactly 2 bits set | Java program to find sum of numbers upto n whose 2 bits are set ; To calculate sum of numbers ; Find numbers whose 2 bits are set ; If number is greater then n we don 't include this in sum ; Return sum of numbers ; Driver program to test findSum ( )
public class Main { static int findSum ( int n ) { int sum = 0 ; for ( int i = 1 ; 1 << i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { int num = ( 1 << i ) + ( 1 << j ) ; if ( num <= n ) sum += num ; } } return sum ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( findSum ( n ) ) ; } }