[LeetCode] Minimum Operations to Make the Integer Zero

2749. Minimum Operations to Make the Integer Zero

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int makeTheIntegerZero(int num1, int num2) {
if(num1 == 0) return 0;
for(long long i = 1; i < 60; i++) {
long long x = num1 - i * num2;
if(x < 0) return -1;
if(__builtin_popcountll(x) <= i and x >= i) return i;
}
return -1;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/25/PS/LeetCode/minimum-operations-to-make-the-integer-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.