Skip to content

2169. Count Operations to Obtain Zero 👍

  • Time: $O(\log(\min(\texttt{num1}, \texttt{num2})))$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int countOperations(int num1, int num2) {
    int ans = 0;

    while (num1 && num2) {
      if (num1 < num2)
        swap(num1, num2);
      ans += num1 / num2;
      num1 %= num2;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int countOperations(int num1, int num2) {
    int ans = 0;

    while (num1 > 0 && num2 > 0) {
      if (num1 < num2) {
        final int temp = num1;
        num1 = num2;
        num2 = temp;
      }
      ans += num1 / num2;
      num1 %= num2;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def countOperations(self, num1: int, num2: int) -> int:
    ans = 0

    while num1 and num2:
      if num1 < num2:
        num1, num2 = num2, num1
      ans += num1 // num2
      num1 %= num2

    return ans