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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code