返回介绍

solution / 0600-0699 / 0693.Binary Number with Alternating Bits / README_EN

发布于 2024-06-17 01:03:35 字数 3702 浏览 0 评论 0 收藏 0

693. Binary Number with Alternating Bits

中文文档

Description

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

 

Example 1:

Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101

Example 2:

Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.

Example 3:

Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.

 

Constraints:

  • 1 <= n <= 231 - 1

Solutions

Solution 1

class Solution:
  def hasAlternatingBits(self, n: int) -> bool:
    prev = -1
    while n:
      curr = n & 1
      if prev == curr:
        return False
      prev = curr
      n >>= 1
    return True
class Solution {
  public boolean hasAlternatingBits(int n) {
    int prev = -1;
    while (n != 0) {
      int curr = n & 1;
      if (prev == curr) {
        return false;
      }
      prev = curr;
      n >>= 1;
    }
    return true;
  }
}
class Solution {
public:
  bool hasAlternatingBits(int n) {
    int prev = -1;
    while (n) {
      int curr = n & 1;
      if (prev == curr) return false;
      prev = curr;
      n >>= 1;
    }
    return true;
  }
};
func hasAlternatingBits(n int) bool {
  prev := -1
  for n != 0 {
    curr := n & 1
    if prev == curr {
      return false
    }
    prev = curr
    n >>= 1
  }
  return true
}
impl Solution {
  pub fn has_alternating_bits(mut n: i32) -> bool {
    let u = n & 3;
    if u != 1 && u != 2 {
      return false;
    }
    while n != 0 {
      if (n & 3) != u {
        return false;
      }
      n >>= 2;
    }
    true
  }
}

Solution 2

class Solution:
  def hasAlternatingBits(self, n: int) -> bool:
    n ^= n >> 1
    return (n & (n + 1)) == 0
class Solution {
  public boolean hasAlternatingBits(int n) {
    n ^= (n >> 1);
    return (n & (n + 1)) == 0;
  }
}
class Solution {
public:
  bool hasAlternatingBits(int n) {
    n ^= (n >> 1);
    return (n & ((long) n + 1)) == 0;
  }
};
func hasAlternatingBits(n int) bool {
  n ^= (n >> 1)
  return (n & (n + 1)) == 0
}
impl Solution {
  pub fn has_alternating_bits(n: i32) -> bool {
    let t = n ^ (n >> 1);
    (t & (t + 1)) == 0
  }
}

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

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

发布评论

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