Leetcode 1342. Number of Steps to Reduce a Number to Zero
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.
Q: Can the input number be negative? A: No, the problem explicitly states that the number is a positive integer.
Q: Is there a maximum limit for the number? A: In general practice, we assume the number fits within the standard integer range (e.g., 32-bit signed integer).
Q: Should we handle special cases where the number is already zero? A: Yes, though if the number is zero, the number of steps is trivially zero.
steps = 0
while num > 0:
if num is even:
num = num / 2
else:
num = num - 1
steps = steps + 1
return steps
The time complexity of this algorithm is O(log N):
public class Solution {
public int numberOfSteps(int num) {
int steps = 0;
while (num > 0) {
if (num % 2 == 0) {
num /= 2;
} else {
num -= 1;
}
steps++;
}
return steps;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.numberOfSteps(14)); // Output: 6
System.out.println(sol.numberOfSteps(8)); // Output: 4
System.out.println(sol.numberOfSteps(123)); // Output: 12
}
}
This code provides a clean and efficient solution to the problem, handling all edge cases specified in the problem statement.
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?