Skip to content
Advertisement

Number of steps to reduce to zero

Hello I have this steps problem and I am trying to see where I can improve my code to get the number of steps it takes to reduce any integer down to zero. I’m sure you all know the process, but just for clarification…if the number is even, we divide by 2, adding a step, and if the number is odd we subtract, adding another step…Can someone let me know what im missing?

JavaScript

Advertisement

Answer

When you write a line such as x / 2, Python will calculate the result of that division. However, you aren’t saving the result of the division anywhere!

You need to do the same thing you’re doing with step += 1, which is equivalent to step = step + 1:

JavaScript

If you don’t do this, the variable int never changes values. It keeps the value it had at the start. And as a result, the while-loop keeps running forever, since abs(int) > 0 stays the case forever.

Another note, int is a built-in type and has special meaning. It is heavily recommended to not use it, or any other such type, as names for your variables. Consider writing integer instead:

JavaScript
Advertisement