[LeetCode] Count Operations to Obtain Zero

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.

  • For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.

Return the number of operations required to make either num1 = 0 or num2 = 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int countOperations(int num1, int num2) {
int op = 0;
if(num1 < num2) swap(num1, num2);
while(num1 and num2) {
op+= num1 / num2;
num1 %= num2;
if(num1 < num2) swap(num1, num2);
}
return op;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/13/PS/LeetCode/count-operations-to-obtain-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.