aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-04-30 11:57:26 -0600
committerJack Sangdahl <[email protected]>2025-04-30 11:57:26 -0600
commit8f773da1404a7c3f1e4a9ccde3d7b33c27d8c3be (patch)
tree736c5c779d8d4726c47faf9548403828823708ac
parent56b6d146c7f33b89c4ef573d0746dc0f306684f0 (diff)
downloadleetcode-8f773da1404a7c3f1e4a9ccde3d7b33c27d8c3be.tar.gz
leetcode-8f773da1404a7c3f1e4a9ccde3d7b33c27d8c3be.zip
2749. minimum operations to make the integer zero
-rw-r--r--min_ops_make_int_zero.c36
-rw-r--r--min_ops_make_int_zero.py39
2 files changed, 75 insertions, 0 deletions
diff --git a/min_ops_make_int_zero.c b/min_ops_make_int_zero.c
new file mode 100644
index 0000000..95d7255
--- /dev/null
+++ b/min_ops_make_int_zero.c
@@ -0,0 +1,36 @@
+// 2749. Minimum Operations to Make the Integer Zero
+#include "leetcode.h"
+
+/*
+ * you are given two integers 'nums1' and 'nums2'. in one operation you can
+ * choose integer 'i' in the range '[0, 60]' and subtract '2^i + num2' from
+ * 'num1'. return the integer denoting the minimum number of operations needed
+ * to make 'nums1' equal to 0. if it is impossible to make 'nums1' equal to 0,
+ * return -1.
+ */
+
+int bit_cnt(long long num) {
+ int cnt = 0;
+ while (num > 0) {
+ cnt += num & 1;
+ num >>= 1;
+ }
+ return cnt;
+}
+
+int makeTheIntegerZero(int num1, int num2) {
+ if (num1 < num2)
+ return -1;
+ for (int i = 0; i <= 100; i++) {
+ long long diff = num1 - 1LL * num2 * i;
+ int bits = bit_cnt(diff);
+ if (bits <= i && i <= diff)
+ return i;
+ }
+ return -1;
+}
+
+int main() {
+ printf("%d\n", makeTheIntegerZero(3, -2)); // expect: 3
+ printf("%d\n", makeTheIntegerZero(5, 7)); // expect: -1
+}
diff --git a/min_ops_make_int_zero.py b/min_ops_make_int_zero.py
new file mode 100644
index 0000000..096921a
--- /dev/null
+++ b/min_ops_make_int_zero.py
@@ -0,0 +1,39 @@
+# 2749. Minimum Operations to Make the Integer Zero
+
+"""
+you are given two integers 'nums1' and 'nums2'. in one operation you can
+choose integer 'i' in the range '[0, 60]' and subtract '2^i + num2' from
+'num1'. return the integer denoting the minimum number of operations needed
+to make 'nums1' equal to 0. if it is impossible to make 'nums1' equal to 0,
+return -1.
+"""
+
+
+class Solution(object):
+ def bit_cnt(self, num):
+ cnt = 0
+ while num > 0:
+ cnt += num & 1
+ num >>= 1
+ return cnt
+
+ def makeTheIntegerZero(self, num1, num2):
+ """
+ :type num1: int
+ :type num2: int
+ :rtype: int
+ """
+ if num1 < num2:
+ return -1
+ for i in range(101):
+ diff = num1 - 1 * num2 * i
+ bits = self.bit_cnt(diff)
+ if bits <= i and i <= diff:
+ return i
+ return -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.makeTheIntegerZero(num1=3, num2=-2))
+ print(obj.makeTheIntegerZero(num1=5, num2=7))