Leetcode 2169. Count Operations to Obtain Zero
You are given two non-negative integers num1
and num2
.
In one operation, if num1 >= num2
, you must subtract num2
from num1
, otherwise subtract num1
from num2
.
num1 = 5
and num2 = 4
, subtract num2
from num1
, thus num1 = 1
and num2 = 4
. However, if num1 = 4
and num2 = 5
, subtract num1
from num2
, thus num1 = 4
and num2 = 1
.Return the number of operations required to make either num1 = 0
or num2 = 0
.
num1
and num2
?
num1
and num2
. Typical constraints are non-negative integers within a practical range, such as 0 ≤ num1
, num2
≤ 10^9.num1
or num2
becomes zero.num1
is greater than or equal to num2
. If true, subtract num2
from num1
.num1
from num2
.The time complexity of the approach is O(max(num1, num2)) in the worst case, where the numbers must be repeatedly subtracted. Due to large potential sizes, we should consider the number of steps carefully.
#include <iostream>
int countOperations(int num1, int num2) {
int operations = 0;
while (num1 != 0 && num2 != 0) {
if (num1 >= num2) {
num1 -= num2;
} else {
num2 -= num1;
}
operations++;
}
return operations;
}
int main() {
int num1 = 12;
int num2 = 15;
std::cout << "Number of operations: " << countOperations(num1, num2) << std::endl;
return 0;
}
In this implementation, we use a simple loop to repeatedly perform the given subtraction operations until one of the numbers becomes zero, counting each operation performed. This should meet the problem requirements efficiently within the standard constraints of competitive programming.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?