Count number of steps to cover a distance if steps can be taken in powers of 2
Given a distance K to cover, the task is to find the minimum steps required to cover the distance if steps can be taken in powers of 2 like 1, 2, 4, 8, 16……..
Examples :
Input : K = 9
Output : 2
Input : K = 343
Output : 6
The minimum steps required can be calculated by reducing K by the highest power of 2 in each step which can be obtained by counting no. of set bits in the binary representation of a number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getMinSteps( int K)
{
return __builtin_popcount(k);
}
int main()
{
int n = 343;
cout << getMinSteps(n)<< '\n' ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getMinSteps( int K)
{
return Integer.bitCount(K);
}
public static void main (String[] args)
{
int n = 343 ;
System.out.println(getMinSteps(n));
}
}
|
Python3
def getMinSteps(K) :
return bin (K).count( "1" )
n = 343
print (getMinSteps(n))
|
C#
using System;
class GFG
{
static int getMinSteps( int K)
{
return countSetBits(K);
}
static int countSetBits( int x)
{
int setBits = 0;
while (x != 0)
{
x = x & (x - 1);
setBits++;
}
return setBits;
}
public static void Main (String[] args)
{
int n = 343;
Console.WriteLine(getMinSteps(n));
}
}
|
Javascript
<script>
function getMinSteps(K)
{
return countSetBits(K);
}
function countSetBits(x)
{
let setBits = 0;
while (x != 0)
{
x = x & (x - 1);
setBits++;
}
return setBits;
}
let n = 343;
document.write(getMinSteps(n));
</script>
|
Time Complexity :
Auxiliary Space: O(1)
Last Updated :
10 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...