Minimum number N such that total set bits of all numbers from 1 to N is at | Javascript implementation of the above approach ; Function to count sum of set bits of all numbers till N ; Function to find the minimum number ; Binary search for the lowest number ; Find mid number ; Check if it is atleast x ; Driver Code
const INF = 99999 ; const size = 10 ; function getSetBitsFromOneToN ( N ) { let two = 2 , ans = 0 ; let n = N ; while ( n ) { ans += parseInt ( N / two ) * ( two >> 1 ) ; if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 ; two <<= 1 ; n >>= 1 ; } return ans ; } function findMinimum ( x ) { let low = 0 , high = 100000 ; let ans = high ; while ( low <= high ) { let mid = ( low + high ) >> 1 ; if ( getSetBitsFromOneToN ( mid ) >= x ) { ans = Math . min ( ans , mid ) ; high = mid - 1 ; } else low = mid + 1 ; } return ans ; } let x = 20 ; document . write ( findMinimum ( x ) ) ;