Guess the Number Using Bitwise Questions II - Problem
There is a number n between 0 and 230 - 1 (both inclusive) that you have to find. There is a pre-defined API int commonBits(int num) that helps you with your mission.
But here is the challenge: every time you call this function, n changes in some way. But keep in mind, that you have to find the initial value of n.
commonBits(int num) acts as follows:
- Calculate
countwhich is the number of bits where bothnandnumhave the same value in that position of their binary representation. n = n XOR num- Return
count.
Return the initial number n.
Note: In this world, all numbers are between 0 and 230 - 1 (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.
Input & Output
Example 1 — Basic Reconstruction
$
Input:
Initial n = 13 (binary: 1101)
›
Output:
13
💡 Note:
Query each bit position: 2^0=1, 2^1=2, 2^2=4, 2^3=8. Use XOR properties to determine original bits and reconstruct n = 1101₂ = 13
Example 2 — All Bits Set
$
Input:
Initial n = 1023 (binary: 1111111111)
›
Output:
1023
💡 Note:
First 10 bits are all 1. Systematic querying reveals each bit, reconstructing the full number
Example 3 — Edge Case Zero
$
Input:
Initial n = 0 (binary: 000...000)
›
Output:
0
💡 Note:
All bits are 0. Each query with powers of 2 will show no matching bits in corresponding positions
Constraints
- 0 ≤ n ≤ 230 - 1
- The API function modifies n with each call
- Only the first 30 bits are considered
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Original number n that we need to find
2
API Call
commonBits(num) counts matching bits, then XORs n
3
Challenge
Find original n despite the changing state
Key Takeaway
🎯 Key Insight: Use powers of 2 as queries to isolate and determine each bit position of the original number
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code