carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2169: Count Operations to Obtain Zero #351

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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.

Example 1:

Input: num1 = 2, num2 = 3 Output: 3 Explanation:

Example 2:

Input: num1 = 10, num2 = 10 Output: 1 Explanation:

Constraints:

0 <= num1, num2 <= 105

carloscn commented 1 year ago

Analysis

int32_t count_operations(int32_t num1, int32_t num2)
{
    int32_t ret = 0;

    while (num1 != 0 && num2 != 0) {
        if (num1 >= num2) {
            num1 = num1 - num2;
        } else {
            num2 = num2 - num1;
        }
        ret ++;
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169568 https://github.com/carloscn/structstudy/commit/b4ca6a02e3214caa4573dbc47944f706b709f84d