![]() |
VOOZH | about |
Given an integer N, the task is to find the number of steps required to reduce the given number N to 1 by performing the following operations:
Examples:
Input: N = 2
Output: 1
Explanation: The given number can be reduced to 1 by following the following steps:
Divide the number by 2 as N is a power of 2 which modifies the N to 1.
Therefore, the N can be reduced to 1 in only 1 step.Input: N = 7
Output: 2
Explanation: The given number can be reduced to 1 by following the following steps:
Subtract 4 the greatest power of 2 less than N. After the step the N modifies to N = 7-4 = 3.
Subtract 2 the greatest power of 2 less than N. After the step the N modifies to N = 3-2 = 1.
Therefore, the N can be reduced to 1 in 2 steps.
Method 1 –
Approach: The idea is to recursively compute the minimum number of steps required.
Below is the implementation of the above approach:
2
Method 2 –
Approach: The given problem can be solved using bitwise operators. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
2
Time Complexity: O(log(N))
Auxiliary Space: O(1)