Simple Approach: 1. Find binary representation of the number using simple decimal to binary representation technique. 2. Count number of set bits in the binary representation equal to ‘n’. 3. Create a binary representation with it’s ‘n’ least significant bits set to 1. 4. Convert the binary representation back to the number. Efficient Approach: 1. Just measure the number of 1’s present in the bit representation of the number. 2. (Number of set bits raised to the power of 2) – 1 represents the minimized number.
// An efficient C++ program to find
// minimum number formed by bits of a given number.
Time Complexity: O(log N), as the _popcnt32 has a time complexity O(logN), however, _popcnt32 has a maximum value of O(log32), so it can be interpreted as O(1) as well. Auxiliary Space: O(1) Note : The above code uses GCC specific functions. If we wish to write code for other compilers, we may use Count set bits in an integer.
Please Login to comment...