2169. Count Operations to Obtain Zero #2399
-
|
Topics: You are given two non-negative integers In one operation, if
Return the number of operations required to make either Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to determine the number of operations required to reduce either of two given non-negative integers to zero by repeatedly subtracting the smaller number from the larger one. The operations continue until one of the numbers becomes zero. Approach
Let's implement this solution in PHP: 2169. Count Operations to Obtain Zero <?php
/**
* @param Integer $num1
* @param Integer $num2
* @return Integer
*/
function countOperations($num1, $num2) {
$count = 0;
while ($num1 > 0 && $num2 > 0) {
if ($num1 >= $num2) {
$count += intdiv($num1, $num2);
$num1 %= $num2;
} else {
$count += intdiv($num2, $num1);
$num2 %= $num1;
}
}
return $count;
}
// Test cases
echo countOperations(2, 3) . PHP_EOL; // Output: 3
echo countOperations(10, 10) . PHP_EOL; // Output: 1
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to determine the number of operations required to reduce either of two given non-negative integers to zero by repeatedly subtracting the smaller number from the larger one. The operations continue until one of the numbers becomes zero.
Approach
num1is greater than or equal tonum2, we calculate how many timesnum2can be subtracted fromnum1using integer division. This count is added to the total operations, andnum1is upd…