vendredi 2 avril 2021

Unable to understand why both the if and else parts are getting executed C#

enter image description here

public class Solution {
public int NumberOfSteps (int num) {
    var steps = 0;
    while(num>0){
        Console.WriteLine(num);
        if((num & 1) == 0){
            num--;
        }
        else{
            num /= 2;
        }
        steps++;
    }
    return steps;
    }
}

This is written in C#. I'm not sure why line number 10 is also getting executed in the same iteration.

IMO the code should loop through for 5 iterations with num being equal to 7 -> 6 -> 3 -> 2 -> 1.

But it is getting executed only 3 times with num value being equal to 7 -> 3 -> 1.

So line number 10 (num /=2) is also getting executed somehow even if the condition is true the else part is also executed.

Link to actual question: LeetCode

Aucun commentaire:

Enregistrer un commentaire