Leetcode 1342. Number of Steps to Reduce a Number to Zero
LeetCode Problem 1342: Number of Steps to Reduce a Number to Zero
Given an integer num
, you need to repeatedly perform the following steps until num
becomes 0:
num
is even, divide it by 2.num
is odd, subtract 1 from it.Return the number of steps to reduce num
to zero.
0 <= num <= 10^6
.num
and initialize a counter to 0.num
is even, divide it by 2.num
is odd, subtract 1 from it.num
is zero.Here’s the C++ function to solve the problem:
#include <iostream>
int numberOfSteps(int num) {
int steps = 0;
while (num > 0) {
if (num % 2 == 0) {
num /= 2;
} else {
num -= 1;
}
steps++;
}
return steps;
}
// Example usage
int main() {
int num = 14;
std::cout << "Number of steps to reduce " << num << " to zero: " << numberOfSteps(num) << std::endl;
return 0;
}
n
is the value of the input number. This is because each division by 2 operation (for even numbers) effectively halves the size of num
, and subtraction operations are constant time.This solution efficiently and correctly follows the steps to reduce the given number to zero.
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?