text: Sum of bit differences for numbers from 0 to N | C # 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
code: using System ; 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 [ i ] == '1' ) { req += find ( binpow ( 2 , i ) ) ; } } return req ; } public static void Main ( ) { int n = 5 ; Console . Write ( totalCountDifference ( n ) ) ; } }