To solve this problem, we need to reduce a given number to zero following these rules:
Given the problem, a clear strategy involves a simple iterative approach:
Here is the implementation of the described strategy:
def numberOfSteps(num: int) -> int:
steps = 0
while num > 0:
if num % 2 == 0:
num //= 2
else:
num -= 1
steps += 1
return steps
# Example Test
print(numberOfSteps(14)) # Output: 6
print(numberOfSteps(8)) # Output: 4
print(numberOfSteps(123)) # Output: 12
In this code:
num
.num
is reduced to zero.num
is even or odd and perform the necessary operation.steps
.This simple iterative approach ensures we handle different cases and reduce the number to zero efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?