Home > Blockchain >  Should I not write a for loop that uses a boolean conditional?
Should I not write a for loop that uses a boolean conditional?

Time:10-21

I was brushing up on the basics and wrote a program that outputs the number of steps required to reduce a number to 0 through dividing by 2 if even, and subtracting 1 if odd. I wrote a for loop in a way I haven't done before and it feels wrong. I wanted to know if there's a reason I shouldn't write a for loop like this.

class Solution {
    public int numberOfSteps(int num) {
        int i;
        for(i = 0; num != 0; i  )
        {
            if(num%2 == 1)
                num--;
            else
                num/=2;
        }
        return i;
    }
}

CodePudding user response:

The for loop used in a way from your example is not the the most readable one because it uses differnet variable for holding its state and different for the break condition. This is not intuitive and many programmers will not see it at first look. The code is ok, it works, and it is a clever way how to use for loop, you save 1 line of code comparing to the while loop, there is really like nothing very wrong there except the unusuall way of using for loop which might hurt readability. That being said I would rather use a while loop for this kind of condition, so it would stand in front what is actually the condition to break the loop. Summing it up, in my opinion approach like the below one would be more readable:

class Solution {
    public int numberOfSteps(int num) {
        int i = 0;
        while(num != 0)
        {
            i  ;
            if(num%2 == 1)
                num--;
            else
                num/=2;
        }
        return i;
    }
}
  •  Tags:  
  • java
  • Related