2169. Count Operations to Obtain Zero
UnknownView on LeetCode
Problem Overview
Count Operations to Obtain Zero (Unknown) asks you to solve a structured algorithmic task. This is a common Math / Simulation pattern in coding interviews. Simulate subtraction (equivalent to Euclidean GCD steps); count operations.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Simulate subtraction (equivalent to Euclidean GCD steps); count operations.
Related patterns: Math, Simulation
2169.cs
C#
// Approach: Simulate subtraction (equivalent to Euclidean GCD steps); count operations.
// Time: O(log(min)) Space: O(1)
public class Solution
{
public int CountOperations(int num1, int num2)
{
// Initialize operation counter
int operationCount = 0;
// Continue operations while both numbers are non-zero
while (num1 != 0 && num2 != 0)
{
// Subtract the smaller number from the larger number
if (num1 >= num2)
num1 -= num2;
else
num2 -= num1;
// Increment the operation counter after each subtraction
operationCount++;
}
// Return the total number of operations performed
return operationCount;
}
}Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 29. Divide Two Integers(Medium)
- 66. Plus One(Easy)
- 67. Add Binary(Easy)
- 68. Text Justification(Hard)