返回介绍

lcci / 05.03.Reverse Bits / README_EN

发布于 2024-06-17 01:04:43 字数 2892 浏览 0 评论 0 收藏 0

05.03. Reverse Bits

中文文档

Description

You have an integer and you can flip exactly one bit from a 0 to a 1. Write code to find the length of the longest sequence of 1s you could create.

Example 1:


Input: num = 1775(110111011112)

Output: 8

Example 2:


Input: num = 7(01112)

Output: 4

Solutions

Solution 1: Two Pointers

We can use two pointers $i$ and $j$ to maintain a sliding window, where $i$ is the right pointer and $j$ is the left pointer. Each time the right pointer $i$ moves one bit to the right, if the number of $0$s in the window exceeds $1$, then the left pointer $j$ moves one bit to the right, until the number of $0$s in the window does not exceed $1$. Then calculate the length of the window at this time, compare it with the current maximum length, and take the larger value as the current maximum length.

Finally, return the maximum length.

The time complexity is $O(\log M)$, and the space complexity is $O(1)$. Here, $M$ is the maximum value of a 32-bit integer.

class Solution:
  def reverseBits(self, num: int) -> int:
    ans = cnt = j = 0
    for i in range(32):
      cnt += num >> i & 1 ^ 1
      while cnt > 1:
        cnt -= num >> j & 1 ^ 1
        j += 1
      ans = max(ans, i - j + 1)
    return ans
class Solution {
  public int reverseBits(int num) {
    int ans = 0, cnt = 0;
    for (int i = 0, j = 0; i < 32; ++i) {
      cnt += num >> i & 1 ^ 1;
      while (cnt > 1) {
        cnt -= num >> j & 1 ^ 1;
        ++j;
      }
      ans = Math.max(ans, i - j + 1);
    }
    return ans;
  }
}
class Solution {
public:
  int reverseBits(int num) {
    int ans = 0, cnt = 0;
    for (int i = 0, j = 0; i < 32; ++i) {
      cnt += num >> i & 1 ^ 1;
      while (cnt > 1) {
        cnt -= num >> j & 1 ^ 1;
        ++j;
      }
      ans = max(ans, i - j + 1);
    }
    return ans;
  }
};
func reverseBits(num int) (ans int) {
  var cnt, j int
  for i := 0; i < 32; i++ {
    cnt += num>>i&1 ^ 1
    for cnt > 1 {
      cnt -= num>>j&1 ^ 1
      j++
    }
    ans = max(ans, i-j+1)
  }
  return
}

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

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

发布评论

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