Given N stairs, the task is to find the minimum number of jumps of perfect power of 2 requires to reach the Nth stair.
Examples:
Input: N = 5
Output:
Explanation:
We can take jumps from 0->1->4.
So the minimum jumps require are 2.Input: N = 23
Output: 4
Explanation:
We can take jumps from 0->1->2->4->16.
So the minimum jumps required are 4.
Approach: Since the jumps are required to be in perfect power of 2. So the count of set bit in the given number N is the minimum number of jumps required to reach Nth stair as the summation of 2i for all set bit index i is equals to N.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include "bits/stdc++.h" using namespace std; // Function to count the number of jumps // required to reach Nth stairs. int stepRequired( int N) { int cnt = 0; // Till N becomes 0 while (N) { // Removes the set bits from // the right to left N = N & (N - 1); cnt++; } return cnt; } // Driver Code int main() { // Number of stairs int N = 23; // Function Call cout << stepRequired(N); return 0; } |
Java
// Java program for the above approach import java.util.*; class GFG{ // Function to count the number of jumps // required to reach Nth stairs. static int stepRequired( int N) { int cnt = 0 ; // Till N becomes 0 while (N > 0 ) { // Removes the set bits from // the right to left N = N & (N - 1 ); cnt++; } return cnt; } // Driver Code public static void main(String[] args) { // Number of stairs int N = 23 ; // Function Call System.out.print(stepRequired(N)); } } // This code is contributed by PrinciRaj1992 |
Python3
# Python3 program for the above approach # Function to count the number of jumps # required to reach Nth stairs. def stepRequired(N): cnt = 0 ; # Till N becomes 0 while (N > 0 ): # Removes the set bits from # the right to left N = N & (N - 1 ); cnt + = 1 ; return cnt; # Driver Code if __name__ = = '__main__' : # Number of stairs N = 23 ; # Function Call print (stepRequired(N)); # This code is contributed by 29AjayKumar |
C#
// C# program for the above approach using System; class GFG{ // Function to count the number of // jumps required to reach Nth stairs. static int stepRequired( int N) { int cnt = 0; // Till N becomes 0 while (N > 0) { // Removes the set bits from // the right to left N = N & (N - 1); cnt++; } return cnt; } // Driver Code public static void Main(String[] args) { // Number of stairs int N = 23; // Function Call Console.Write(stepRequired(N)); } } // This code is contributed by 29AjayKumar |
4
Time Complexity: O(log N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.