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 ofn.
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 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.
Constraints:
0 <= n <= 230 - 10 <= num <= 230 - 1- If you ask for some
numout of the given range, the output wouldn’t be reliable.
Examples
Example 1
| |
Example 2
| |
Constraints
0 <= n <= 2^30 - 10 <= num <= 2^30 - 1- If you ask for some
numout of the given range, the output wouldn’t be reliable.
Solution
Method 1 – Bitwise Simulation and XOR Reversal
Intuition
Each call to commonBits(num) both reveals information about the current n and mutates it by n = n ^ num. To recover the initial value, we can simulate the process: for each bit, query with a mask for that bit, record the result, and keep track of the cumulative XOR of all queries. After all queries, the initial value is the XOR of the final n and the cumulative XOR of all queries.
Approach
- For each bit position from 0 to 29:
- Query with
num = 1 << i. - If the result is 30, the bit in
nmatches the bit innum(i.e., the bit is set inn). - Accumulate the XOR of all queries.
- Query with
- After all queries, the current
nis the result of applying all XORs to the initial value. - The initial value is the XOR of the current
nand the cumulative XOR of all queries. - Return the reconstructed initial value.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(1)— Always 30 queries, regardless of the value ofn. - 🧺 Space complexity:
O(1)— Only a few variables are used.