Guess the Number Using Bitwise Questions I - Problem

There is a number n that you have to find. There is also a pre-defined API int commonSetBits(int num), which returns the number of bits where both n and num are 1 in that position of their binary representation.

In other words, it returns the number of set bits in n & num, where & is the bitwise AND operator.

Return the number n.

Input & Output

Example 1 — Target is 13
$ Input: n = 13 (binary: 1101)
Output: 13
💡 Note: Test powers of 2: commonSetBits(1)=1, commonSetBits(2)=0, commonSetBits(4)=1, commonSetBits(8)=1. This gives us bits 0,2,3 are set, so n = 1+4+8 = 13
Example 2 — Target is 7
$ Input: n = 7 (binary: 111)
Output: 7
💡 Note: Test: commonSetBits(1)=1, commonSetBits(2)=1, commonSetBits(4)=1, commonSetBits(8)=0. Bits 0,1,2 are set, so n = 1+2+4 = 7
Example 3 — Target is 1
$ Input: n = 1 (binary: 1)
Output: 1
💡 Note: Test: commonSetBits(1)=1, commonSetBits(2)=0, commonSetBits(4)=0. Only bit 0 is set, so n = 1

Constraints

  • 1 ≤ n ≤ 230
  • You can call the API at most 30 times

Visualization

Tap to expand
Guess the Number: Finding n=13 using commonSetBits APIStep 1: Unknown Targetn = ?Hidden numberStep 2: Test with Powers of 21248commonSetBits(1,2,4,8...)Step 3: API Responses1011Response: bits setResult: Binary10111101₂Algorithm: Test each bit position with powers of 2commonSetBits(1) = 1 → bit 0 is setcommonSetBits(2) = 0 → bit 1 is not setcommonSetBits(4) = 1 → bit 2 is setcommonSetBits(8) = 1 → bit 3 is setFinal Answer: n = 1 + 4 + 8 = 13Time: O(log n), Space: O(1) - Only 31 API calls maximum
Understanding the Visualization
1
Unknown Target
We need to find n, only knowing commonSetBits API
2
Strategic Testing
Test with powers of 2 to isolate each bit
3
Reconstruct Number
Combine detected bits to form the answer
Key Takeaway
🎯 Key Insight: Each bit can be detected independently by testing with its corresponding power of 2
Asked in
Google 15 Microsoft 12 Amazon 8
12.3K Views
Medium Frequency
~15 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen