Largest number less than X having at most K set bits
Last Updated :
24 Nov, 2022
Given an integer X > 1 and an integer K > 0, the task is to find the greatest odd number < X such that the number of 1’s in its binary representation is at most K.
Examples:
Input: X = 10, K = 2
Output: 10
Input: X = 29, K = 2
Output: 24
Naive Approach: Starting from X – 1 check all the numbers below X which have at most K set bits, the first number satisfying the condition is the required answer.
Efficient Approach: is to count the set bits. If the count is less than or equal to K, return X. Otherwise, keep removing rightmost set bit while count – k does not become 0.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int greatestKBits( int X, int K)
{
int set_bit_count = __builtin_popcount(X);
if (set_bit_count <= K)
return X;
int diff = set_bit_count - K;
for ( int i = 0; i < diff; i++)
X &= (X - 1);
return X;
}
int main()
{
int X = 21, K = 2;
cout << greatestKBits(X, K);
return 0;
}
|
Java
import java.io.*;
class GFG {
int greatestKBits( int X, int K)
{
int set_bit_count = Integer.bitCount(X);
if (set_bit_count <= K)
return X;
int diff = set_bit_count - K;
for ( int i = 0 ; i < diff; i++)
X &= (X - 1 );
return X;
}
public static void main (String[] args)
{
int X = 21 , K = 2 ;
GFG g= new GFG();
System.out.print(g.greatestKBits(X, K));
}
}
|
Python3
def greatestKBits(X, K):
set_bit_count = bin (X).count( '1' )
if (set_bit_count < = K):
return X
diff = set_bit_count - K
for i in range ( 0 , diff, 1 ):
X & = (X - 1 )
return X
if __name__ = = '__main__' :
X = 21
K = 2
print (greatestKBits(X, K))
|
C#
using System;
class GFG
{
static int countSetBits( int n)
{
int count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
static int greatestKBits( int X, int K)
{
int set_bit_count = countSetBits(X);
if (set_bit_count <= K)
return X;
int diff = set_bit_count - K;
for ( int i = 0; i < diff; i++)
X &= (X - 1);
return X;
}
public static void Main()
{
int X = 21, K = 2;
Console.WriteLine(greatestKBits(X, K));
}
}
|
Javascript
<script>
function countSetBits( n)
{
let count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
function greatestKBits( X, K)
{
let set_bit_count = countSetBits(X);
if (set_bit_count <= K)
return X;
let diff = set_bit_count - K;
for (let i = 0; i < diff; i++)
X &= (X - 1);
return X;
}
let X = 21, K = 2;
document.write(greatestKBits(X, K));
</script>
|
Time Complexity: O(log2X), as the time complexity of __builtin_popcount(X) is O(log2X)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...