Talentd
FleetCode

3094. Guess the Number Using Bitwise Questions II

Medium81.8% acceptancePremium elsewhere, free here

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.

Constraints:

  • 0 <= n <= 230 - 1
  • 0 <= num <= 230 - 1
  • If you ask for some num out of the given range, the output wouldn't be reliable.

Hints open one at a time

Hint 1
Ask the number 0 and save the result in base.
Hint 2
Ask 2i for 0 <= i < 30.
Hint 3
If the result is greater than base for some i, then this bit is a set bit in n.
Hint 4
What can be done to revert the effect of the XOR.
Hint 5
Doing XOR again with the same number reverts the effect.
5:34
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
31
Your code is saved on this device.Solution