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 count which is the number of bits where both n and num have 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
Interactive Bitwise Number Guessing ProblemOriginal n(Unknown)commonBits(num)1. Count matches2. n = n XOR numModified n(Changed)Example: n = 13 (1101₂), query = 5 (0101₂)n: 1101query: 0101Common: 2(bits 0,2)n XOR 5= 1000 = 8Challenge: Find original n despite XOR modificationsSolution: Query systematically with powers of 2
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
Asked in
Google 25 Microsoft 18 Facebook 15
28.5K Views
Medium Frequency
~35 min Avg. Time
890 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