给定N个楼梯,任务是找到达到第N个楼梯所需的2次幂的最小跳跃数。
例子:
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.
方法:由于要求跳数必须为2的整数幂,因此给定数N中的设置位的计数是达到第N个楼梯所需的最小跳数,因为所有设置位索引i的2 i之和为等于N。
下面是上述方法的实现:
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
Javascript
输出:
4
时间复杂度: O(log N)