返回介绍

solution / 3000-3099 / 3064.Guess the Number Using Bitwise Questions I / README_EN

发布于 2024-06-17 01:02:57 字数 4630 浏览 0 评论 0 收藏 0

3064. Guess the Number Using Bitwise Questions I

中文文档

Description

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 <= 230 - 1
  • 0 <= num <= 230 - 1
  • If you ask for some num out of the given range, the output wouldn't be reliable.

Solutions

Solution 1: Enumeration

We can enumerate the powers of 2, and then call the commonSetBits method. If the return value is greater than 0, it means that the corresponding bit in the binary representation of n is 1.

The time complexity is $O(\log n)$, where $n \le 2^{30}$ in this problem. The space complexity is $O(1)$.

# Definition of commonSetBits API.
# def commonSetBits(num: int) -> int:


class Solution:
  def findNumber(self) -> int:
    return sum(1 << i for i in range(32) if commonSetBits(1 << i))
/**
 * Definition of commonSetBits API (defined in the parent class Problem).
 * int commonSetBits(int num);
 */

public class Solution extends Problem {
  public int findNumber() {
    int n = 0;
    for (int i = 0; i < 32; ++i) {
      if (commonSetBits(1 << i) > 0) {
        n |= 1 << i;
      }
    }
    return n;
  }
}
/**
 * Definition of commonSetBits API.
 * int commonSetBits(int num);
 */

class Solution {
public:
  int findNumber() {
    int n = 0;
    for (int i = 0; i < 32; ++i) {
      if (commonSetBits(1 << i)) {
        n |= 1 << i;
      }
    }
    return n;
  }
};
/**
 * Definition of commonSetBits API.
 * func commonSetBits(num int) int;
 */

func findNumber() (n int) {
  for i := 0; i < 32; i++ {
    if commonSetBits(1<<i) > 0 {
      n |= 1 << i
    }
  }
  return
}
/**
 * Definition of commonSetBits API.
 * var commonSetBits = function(num: number): number {}
 */

function findNumber(): number {
  let n = 0;
  for (let i = 0; i < 32; ++i) {
    if (commonSetBits(1 << i)) {
      n |= 1 << i;
    }
  }
  return n;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文