Skip to content

3064. Guess the Number Using Bitwise Questions I

  • Time: $O(30) = O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/**
 * Definition of commonSetBits API.
 * int commonSetBits(int num);
 */

class Solution {
 public:
  int findNumber() {
    constexpr int kMaxBit = 30;
    int ans = 0;
    for (int i = 0; i <= kMaxBit; ++i)
      if (commonSetBits(1 << i) == 1)
        ans |= 1 << i;
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
/**
 * Definition of commonSetBits API (defined in the parent class Problem).
 * int commonSetBits(int num);
 */

public class Solution extends Problem {
  public int findNumber() {
    final int MAX_BIT = 30;
    int ans = 0;
    for (int i = 0; i <= MAX_BIT; ++i)
      if (commonSetBits(1 << i) == 1)
        ans |= 1 << i;
    return ans;
  }
}
1
2
3
4
5
6
7
# Definition of commonSetBits API.
# def commonSetBits(num: int) -> int:

class Solution:
  def findNumber(self) -> int:
    return sum(1 << i for i in range(31)
               if commonSetBits(1 << i) == 1)