1342. Number of Steps to Reduce a Number to Zero LeetCode Solution
In this guide, you will get 1342. Number of Steps to Reduce a Number to Zero LeetCode Solution with the best time and space complexity. The solution to Number of Steps to Reduce a Number to Zero problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Number of Steps to Reduce a Number to Zero solution in C++
- Number of Steps to Reduce a Number to Zero solution in Java
- Number of Steps to Reduce a Number to Zero solution in Python
- Additional Resources
Problem Statement of 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.
Example 1:
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
Constraints:
0 <= num <= 106
Complexity Analysis
- Time Complexity: O(1)
- Space Complexity: O(1)
1342. Number of Steps to Reduce a Number to Zero LeetCode Solution in C++
class Solution {
public:
int numberOfSteps(unsigned num) {
if (num == 0)
return 0;
const int subtractSteps = popcount(num);
const int divideSteps = 31 - __builtin_clz(num);
return subtractSteps + divideSteps;
}
};
/* code provided by PROGIEZ */
1342. Number of Steps to Reduce a Number to Zero LeetCode Solution in Java
class Solution {
public int numberOfSteps(int num) {
if (num == 0)
return 0;
final int subtractSteps = Integer.bitCount(num);
final int divideSteps = 31 - Integer.numberOfLeadingZeros(num);
return subtractSteps + divideSteps;
}
}
// code provided by PROGIEZ
1342. Number of Steps to Reduce a Number to Zero LeetCode Solution in Python
class Solution:
def numberOfSteps(self, num: int) -> int:
if num == 0:
return 0
subtractSteps = num.bit_count()
divideSteps = num.bit_length() - 1
return subtractSteps + divideSteps
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.