Input: num1 =3, num2 =-2Output: 3Explanation: We can make 3 equal to 0with 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 3is the minimum number of operations that we need to perform.
The operation subtracts (2^i + num2) from num1. To reach zero, we need to find a sequence of such operations. The key is to notice that after k operations, num1 + k * num2 must be a sum of k powers of two, i.e., it must be possible to write num1 + k * num2 as a sum of k distinct powers of two (which is equivalent to having at least k bits set in its binary representation).
classSolution {
public:int minOperations(int num1, int num2) {
for (int k =1; k <=60; ++k) {
longlong x = num1 +1LL* k * num2;
if (x <=0) continue;
if (__builtin_popcountll(x) <= k) return k;
}
return-1;
}
};
classSolution {
publicintminOperations(int num1, int num2) {
for (int k = 1; k <= 60; k++) {
long x = num1 + 1L * k * num2;
if (x <= 0) continue;
if (Long.bitCount(x) <= k) return k;
}
return-1;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funminOperations(num1: Int, num2: Int): Int {
for (k in1..60) {
val x = num1.toLong() + k * num2.toLong()
if (x <=0) continueif (x.countOneBits() <= k) return k
}
return -1 }
}
1
2
3
4
5
6
7
8
9
classSolution:
defminOperations(self, num1: int, num2: int) -> int:
for k in range(1, 61):
x = num1 + k * num2
if x <=0:
continueif bin(x).count('1') <= k:
return k
return-1
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmin_operations(num1: i32, num2: i32) -> i32 {
for k in1..=60 {
let x = num1 asi64+ k asi64* num2 asi64;
if x <=0 { continue; }
if x.count_ones() asi32<= k {
return k;
}
}
-1 }
}
1
2
3
4
5
6
7
8
9
10
classSolution {
minOperations(num1: number, num2: number):number {
for (letk=1; k<=60; k++) {
constx=num1+k*num2;
if (x<=0) continue;
if (x.toString(2).split('1').length-1<=k) returnk;
}
return-1;
}
}