Sum of bit differences for numbers from 0 to N | Java program for the above approach ; Function to implement fast exponentiation ; Function to return the value for powers of 2 ; Function to convert N into binary ; To store the binary representation ; Iterate each digit of n ; Return binary representation ; Function to find difference in bits ; Get binary representation ; total number of bit differences from 0 to N ; Iterate over each binary bit ; If current bit is '1' then add the count of current bit ; Driver code ; Given number ; Function Call
import java . io . * ; import java . lang . Math ; class GFG { static int binpow ( int a , int b ) { int res = 1 ; while ( b > 0 ) { if ( b % 2 == 1 ) res = res * a ; a = a * a ; b /= 2 ; } return res ; } static int find ( int x ) { if ( x == 0 ) return 0 ; int p = ( int ) ( Math . log ( x ) / Math . log ( 2 ) ) ; return binpow ( 2 , p + 1 ) - 1 ; } static String getBinary ( int n ) { String ans = " " ; while ( n > 0 ) { int dig = n % 2 ; ans += dig ; n /= 2 ; } return ans ; } static int totalCountDifference ( int n ) { String ans = getBinary ( n ) ; int req = 0 ; for ( int i = 0 ; i < ans . length ( ) ; i ++ ) { if ( ans . charAt ( i ) == '1' ) { req += find ( binpow ( 2 , i ) ) ; } } return req ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( totalCountDifference ( n ) ) ; } }