I keep performing the subtraction operation until either number becomes zero. In each step, I subtract the smaller number from the larger one and count how many operations it takes. Since this process is similar to finding the GCD using subtraction, it ends when one number hits zero.
class Solution:
def countOperations(self, num1: int, num2: int) -> int:
count = 0
while num1 > 0 and num2 > 0:
if num1 >= num2:
num1 -= num2
else:
num2 -= num1
count += 1
return count- Time: O(max(num1, num2))
- Space: O(1)