Count total set bits in all numbers from 1 to n | Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver Code
< ? php function countSetBits ( $ n ) { $ bitCount = 0 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ bitCount += countSetBitsUtil ( $ i ) ; return $ bitCount ; } function countSetBitsUtil ( $ x ) { if ( $ x <= 0 ) return 0 ; return ( $ x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( $ x / 2 ) ; } $ n = 4 ; echo " Total ▁ set ▁ bit ▁ count ▁ is ▁ " . countSetBits ( $ n ) ; ? >