
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Largest number less than X having at most K set bits in C++
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.
Example
Let's see the code.
#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; }
Output
If you run the above code, then you will get the following result.
65
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
- Related Articles
- Previous smaller integer having one less number of set bits in C++
- Largest subarray having sum greater than k in C++
- Find the Number of subarrays having sum less than K using C++
- Largest permutation after at most k swaps in C++
- Count all subsequences having product less than K in C++
- Count the number of words having sum of ASCII values less than and greater than k in C++
- Count of alphabets having ASCII value less than and greater than k in C++
- Largest K digit number divisible by X in C++
- Next greater integer having one more number of set bits in C++
- Count of divisors having more set bits than quotient on dividing N in C++
- Find the largest number with n set and m unset bits in C++
- Subarray Product Less Than K in C++
- Minimum flips required to maximize a number with k set bits in C++.
- C++ Program for Largest K digit number divisible by X?
- Form the largest number using at most one swap operation C++

Advertisements