Guess the Number Using Bitwise Questions II Problem
Description
LeetCode Problem 3094.
There is a number n between 0 and 2^30 - 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
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 2^30 - 1 (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.
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
Approach: Bit Manipulation
Two facts about commonBits(num):
- Calling it twice with the same
numrestoresn, becausenis XORed withnumtwice. - Calling
commonBits(1 << i)flips only bitiofn.
For each bit i from 0 to 29, call commonBits(1 << i) twice. The first call counts bit i as it originally is; the second counts it after the flip, while all other bits are unchanged. So count1 > count2 exactly when bit i of n was 1. Set that bit in the answer.
Complexity: O(log n) calls (60), O(1) space.
# Definition of commonBits API.
# def commonBits(num: int) -> int:
class Solution:
def findNumber(self) -> int:
n = 0
for i in range(30):
count1 = commonBits(1 << i)
count2 = commonBits(1 << i)
if count1 > count2:
n |= 1 << i
return n