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 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 — Original n = 13
$ Input: Original n = 13 (binary: 1101)
Output: 13
💡 Note: Using strategic bit queries, we determine bit 0=1, bit 2=1, bit 3=1, others=0, reconstructing 1101₂ = 13
Example 2 — Original n = 7
$ Input: Original n = 7 (binary: 0111)
Output: 7
💡 Note: Query each bit position to find bits 0, 1, 2 are set, giving us 0111₂ = 7
Example 3 — Original n = 0
$ Input: Original n = 0 (binary: 0000...)
Output: 0
💡 Note: All commonBits queries return maximum count since all bits match, indicating original was 0

Constraints

  • 0 ≤ n ≤ 230 - 1
  • Only first 30 bits are considered
  • Each commonBits() call modifies n with XOR operation

Visualization

Tap to expand
INPUTHidden Number nOriginal n = 13Binary: 1101API Available:commonBits(num):1. Count matching bits2. n = n XOR num3. Return countChallenge: n changes!ALGORITHMBit-by-Bit Reconstruction1Query each bit position i2Call commonBits(2^i)3Compare with baseline4Determine bit valueBit 0: Test with 1Bit 2: Test with 4Bit 3: Test with 8Result: 1101₂RESULTOriginal Number Foundn = 13Binary: 1101Complexity:Time: O(log n)Space: O(1)API Calls: ~60(2 per bit × 30 bits)Key Insight:Each bit can be determined independently using strategic XOR queriesTutorialsPoint - Guess the Number Using Bitwise Questions II | Bit Manipulation
Asked in
Google 25 Microsoft 18 Amazon 15 Facebook 12
23.4K Views
Medium Frequency
~35 min Avg. Time
856 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