📌  相关文章
📜  如果可以以2的幂进行步数,则计算覆盖距离的步数

📅  最后修改于: 2021-05-25 01:46:23             🧑  作者: Mango

给定要覆盖的距离K,如果能以1、2、4、8、16……的2的幂采取步长,则任务是找到覆盖该距离所需的最小步长。

例子 :

Input : K = 9
Output : 2

Input : K = 343 
Output : 6

可以通过在每个步骤中将K减去2的最高幂来计算所需的最小步骤,这可以通过计算no来获得。数字的二进制表示形式中的置位数。

下面是上述方法的实现:

C++
// C++ program to count the minimum number of steps 
  
#include 
using namespace std;
  
// Function to count the minimum number of steps
int getMinSteps(int K)
{
   // __builtin_popcount() is a C++ function to 
   // count the number of set bits in a number
   return __builtin_popcount(k);
}
  
// Driver Code
int main()
{
    int n = 343;
      
    cout << getMinSteps(n)<< '\n';
  
    return 0;
}


Java
// Java program to count minimum number of steps 
import java.io.*;
  
class GFG
{
      
    // Function to count the minimum number of steps 
    static int getMinSteps(int K) 
    { 
        // count the number of set bits in a number 
        return Integer.bitCount(K);
    } 
      
    // Driver Code 
    public static void main (String[] args)
    { 
        int n = 343; 
          
        System.out.println(getMinSteps(n)); 
    } 
}
  
// This code is contributed by AnkitRai01


Python3
# Python 3 implementation of the approach 
  
# Function to count the minimum number of steps 
def getMinSteps(K) :
      
    # bin(K).count("1") is a Python3 function to 
    # count the number of set bits in a number 
    return bin(K).count("1")
  
# Driver Code 
n = 343
print(getMinSteps(n))
  
# This code is contributed by
# divyamohan123


C#
// C# program to count minimum number of steps
using System;
      
class GFG
{
      
    // Function to count the minimum number of steps 
    static int getMinSteps(int K) 
    { 
        // count the number of set bits in a number 
        return countSetBits(K);
    } 
      
    static int countSetBits(int x)
    {
        int setBits = 0;
        while (x != 0)
        {
            x = x & (x - 1);
            setBits++;
        }
        return setBits;
    }
      
    // Driver Code 
    public static void Main (String[] args)
    { 
        int n = 343; 
          
        Console.WriteLine(getMinSteps(n)); 
    } 
}
  
// This code is contributed by 29AjayKumar


输出:
6

时间复杂度:  O(log(n))

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。