返回介绍

solution / 1600-1699 / 1611.Minimum One Bit Operations to Make Integers Zero / README_EN

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

1611. Minimum One Bit Operations to Make Integers Zero

中文文档

Description

Given an integer n, you must transform it into 0 using the following operations any number of times:

  • Change the rightmost (0th) bit in the binary representation of n.
  • Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.

Return _the minimum number of operations to transform _n_ into _0_._

 

Example 1:

Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.

Example 2:

Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.

 

Constraints:

  • 0 <= n <= 109

Solutions

Solution 1

class Solution:
  def minimumOneBitOperations(self, n: int) -> int:
    ans = 0
    while n:
      ans ^= n
      n >>= 1
    return ans
class Solution {
  public int minimumOneBitOperations(int n) {
    int ans = 0;
    for (; n > 0; n >>= 1) {
      ans ^= n;
    }
    return ans;
  }
}
class Solution {
public:
  int minimumOneBitOperations(int n) {
    int ans = 0;
    for (; n > 0; n >>= 1) {
      ans ^= n;
    }
    return ans;
  }
};
func minimumOneBitOperations(n int) (ans int) {
  for ; n > 0; n >>= 1 {
    ans ^= n
  }
  return
}
function minimumOneBitOperations(n: number): number {
  let ans = 0;
  for (; n > 0; n >>= 1) {
    ans ^= n;
  }
  return ans;
}

Solution 2

class Solution:
  def minimumOneBitOperations(self, n: int) -> int:
    if n == 0:
      return 0
    return n ^ self.minimumOneBitOperations(n >> 1)
class Solution {
  public int minimumOneBitOperations(int n) {
    if (n == 0) {
      return 0;
    }
    return n ^ minimumOneBitOperations(n >> 1);
  }
}
class Solution {
public:
  int minimumOneBitOperations(int n) {
    if (n == 0) {
      return 0;
    }
    return n ^ minimumOneBitOperations(n >> 1);
  }
};
func minimumOneBitOperations(n int) int {
  if n == 0 {
    return 0
  }
  return n ^ minimumOneBitOperations(n>>1)
}
function minimumOneBitOperations(n: number): number {
  if (n === 0) {
    return 0;
  }
  return n ^ minimumOneBitOperations(n >> 1);
}

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

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

发布评论

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