VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-number-using-bitwise-questions-i/

⇱ Find the Number Using Bitwise Questions I - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the Number Using Bitwise Questions I

Last Updated : 23 Jul, 2025

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:

  • findNumber Function:
    • This function calculates the number by iterating through the first 31 bits (from 0 to 30).
    • For each bit position i, it checks if commonSetBits(1 << i) is non-zero.
    • If the condition is true, it adds 1 << i (which is equivalent to 2^i) to val.

Below is the implementation of the above approach:


Output
The result is: 1

Time Complexity: O(1)
Auxiliary Space: O(1)


Comment
Article Tags:
Article Tags: