#1342
Easy Algorithms Number of steps to reduce a number to zero
Math Bit Manipulation
85.7% acceptance
Feb 25, 2026
4261
181
Given an integer num, return the number of steps to reduce it to zero.
In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn number_of_steps(mut num: i32) -> i32 {
let mut steps = 0;
while num > 0 {
if num % 2 == 0 { num /= 2; } else { num -= 1; }
steps += 1;
}
steps
}
}