Guess the Number Using Bitwise Questions I Problem
#3064
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3064.
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.
Example 1:
Input: n = 31
Output: 31
Explanation: It can be proven that it's possible to find 31 using the provided API.
Example 2:
Input: n = 33
Output: 33
Explanation: It can be proven that it's possible to find 33 using the provided API.
Constraints:
1 <= 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: Enumeration
Ask about each power of two. commonSetBits(1 << i) returns 1 exactly when bit i of n is set, so we set that bit in the answer whenever the result is greater than 0. Since n < 2^30, 30 queries are enough.
Complexity: O(log n) time and O(1) extra space, where n < 2^30 here.
# Definition of commonSetBits API.
# def commonSetBits(num: int) -> int:
class Solution:
def findNumber(self) -> int:
return sum(1 << i for i in range(30) if commonSetBits(1 << i))