![]() |
VOOZH | about |
Given a task to find a number n. There is a pre-defined API int commonSetBits(int val) that returns the number of bits where both n and val have a value of 1 in the corresponding position of their binary representation. In other words, it returns the number of set bits in the bitwise AND (&) operation of n and val. The task is to return the number n.
Example:
Input: n = 31
Output: 31
Explanation: It can be proven that it's possible to find 31 using the provided API.Input: n = 33
Output: 33
Explanation: It can be proven that it's possible to find 33 using the provided API.
Approach:
To find the bits of a hidden number using the magic function with binary numbers that have only one 1 in them, we can follow this approach:
Get the binary numbers by performing a left shift operation on 1 and adding the numbers as: ∑ for n = 0 to n = 30 (2^n * (1 * bitPresentOrNot)
Steps-by-step approach:
Below is the implementation of the above approach:
The result is: 1
Time Complexity: O(1)
Auxiliary Space: O(1)