Largest number less than X having at most K set bits in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the largest number which is less than given x and should have at most k set bits.

Let's see the steps to solve the problem.

  • Initialise the numbers x and k.
  • Find the set bits in the number x.
  • Write a loop that iterates set bits count of x - k.
    • Update the value of x with x & (x - 1).
  • Return x.


Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int largestNumberWithKBits(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 = 65, k = 2;
   cout << largestNumberWithKBits(x, k) << endl;
   return 0;


If you run the above code, then you will get the following result.



If you have any queries in the tutorial, mention them in the comment section.

Updated on 09-Apr-2021 13:34:07