返回介绍

solution / 2700-2799 / 2749.Minimum Operations to Make the Integer Zero / README_EN

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

2749. Minimum Operations to Make the Integer Zero

中文文档

Description

You are given two integers num1 and num2.

In one operation, you can choose integer i in the range [0, 60] and subtract 2i + num2 from num1.

Return _the integer denoting the minimum number of operations needed to make_ num1 _equal to_ 0.

If it is impossible to make num1 equal to 0, return -1.

 

Example 1:

Input: num1 = 3, num2 = -2
Output: 3
Explanation: We can make 3 equal to 0 with the following operations:
- We choose i = 2 and substract 22 + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and substract 22 + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and substract 20 + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.

Example 2:

Input: num1 = 5, num2 = 7
Output: -1
Explanation: It can be proven, that it is impossible to make 5 equal to 0 with the given operation.

 

Constraints:

  • 1 <= num1 <= 109
  • -109 <= num2 <= 109

Solutions

Solution 1

class Solution:
  def makeTheIntegerZero(self, num1: int, num2: int) -> int:
    for k in count(1):
      x = num1 - k * num2
      if x < 0:
        break
      if x.bit_count() <= k <= x:
        return k
    return -1
class Solution {
  public int makeTheIntegerZero(int num1, int num2) {
    for (long k = 1;; ++k) {
      long x = num1 - k * num2;
      if (x < 0) {
        break;
      }
      if (Long.bitCount(x) <= k && k <= x) {
        return (int) k;
      }
    }
    return -1;
  }
}
class Solution {
public:
  int makeTheIntegerZero(int num1, int num2) {
    using ll = long long;
    for (ll k = 1;; ++k) {
      ll x = num1 - k * num2;
      if (x < 0) {
        break;
      }
      if (__builtin_popcountll(x) <= k && k <= x) {
        return k;
      }
    }
    return -1;
  }
};
func makeTheIntegerZero(num1 int, num2 int) int {
  for k := 1; ; k++ {
    x := num1 - k*num2
    if x < 0 {
      break
    }
    if bits.OnesCount(uint(x)) <= k && k <= x {
      return k
    }
  }
  return -1
}

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

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

发布评论

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