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 Using Bitwise Questions INPUT Hidden Number n = ? We need to find n bit by bit Bit Positions: 3 2 1 0 API: commonSetBits(num) Returns bits where n AND num = 1 Test Queries: commonSetBits(1) = ? commonSetBits(2) = ? commonSetBits(4) = ? commonSetBits(8) = ? Query with powers of 2 ALGORITHM STEPS 1 Initialize result = 0 Start with empty number 2 Loop: i = 0 to 30 Check each bit position 3 Query: 1 << i Call commonSetBits(1<<i) 4 If result > 0 Set bit: result |= (1<<i) Example: n = 13 (1101) i=0: query(1) --> 1 SET i=1: query(2) --> 0 SKIP i=2: query(4) --> 1 SET i=3: query(8) --> 1 SET FINAL RESULT Building result bit by bit: 1 8 1 4 0 2 1 1 Binary: 1101 8 + 4 + 0 + 1 = 13 Decimal Value Output: 13 Number found! Verification: n = 13 = 1101 (binary) OK - Correct! Key Insight: By querying commonSetBits() with powers of 2 (1, 2, 4, 8...), we isolate each bit position. If the API returns 1 for query(2^i), then bit i is set in n. We reconstruct n by ORing all set bits. Time: O(log n) queries | Space: O(1) | Optimal bit-by-bit detection approach TutorialsPoint - Guess the Number Using Bitwise Questions I | Optimized Bit Detection
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