Sheharyar  Khan
Sheharyar Khan

Reputation: 43

Count Operations to Obtain Zero

Given two non-negative integers num1 and num2.

In an 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.

I am trying to do this question on leetcode. I take a count=0 then take a while loop eventually do the basic logic to count no of operation in which one the given reduces to 0. But why I am getting the time limit exceded when I try to run the following code for the same

#Here is my code for the same

class Solution {
    public int countOperations(int num1, int num2) {
        int count =0;
        while(num1>=0 && num2>=0){
            if(num1>=num2){
                num1=num1-num2;
                count++;
            }else{
                num2=num2-num1;
                count++;
            }
        }
        return count;
    }
}

Upvotes: 0

Views: 239

Answers (3)

Sheharyar  Khan
Sheharyar Khan

Reputation: 43

Here is the correct answer. Here both numbers have to be greater than 0. so I put the condition while (num1>0 && num2>0).
Here the code for the same

class Solution {
public int countOperations(int num1, int num2) {
    int count =0;
    while(num1!=0 && num2!=0){
        if(num1>=num2){
            num1=num1-num2;
            count++;
        }else{
            num2=num2-num1;
            count++;
        }
    }
    return count;
}

}

Upvotes: 0

EarlGrey
EarlGrey

Reputation: 531

The condition of your while loop is not correct.
You have to do the algorithm as long as both numbers are greater than 0.
Your code runs as long as both numbers are 0 or more. This will never terminate, as this would mean, num1 and num2 had to become negative.
Instead you must end the loop, as soon as one number is 0.

Upvotes: 2

bug
bug

Reputation: 1

you two parameter will to statisfy you condition when they run

Upvotes: 0

Related Questions