
- 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
Previous smaller integer having one less number of set bits in C++
In this problem, we are given an integer n. Our task is to print the largest number less than n which can be formed by changing one set bit of the binary representation of the number.
Let’s take an example to understand the problem
Input: n = 3 Output: 2 Explanation: (3)10 = (011)2 Flipping one set bit gives 001 and 010. 010 is greater i.e. 2.
To solve this problem, we will have to flip the rightmost set bit and make it zero which will create the number the greatest possible number less than n that is found by flipping one bit of the number.
Program to show the implementation of our solution,
Example
#include<iostream> #include<math.h> using namespace std; int returnRightSetBit(int n) { return log2(n & -n) + 1; } void previousSmallerInteger(int n) { int rightBit = returnRightSetBit(n); cout<<(n&~(1<<(rightBit - 1))); } int main() { int n = 3452; cout<<"The number is "<<n<<"\nThe greatest integer smaller than the number is : "; previousSmallerInteger(n); return 0; }
Output
The number is 3452 The greatest integer smaller than the number is : 3448
- Related Articles
- Next greater integer having one more number of set bits in C++
- Largest number less than X having at most K set bits in C++
- Count set bits in an integer in C++
- C/C++ Program to Count set bits in an integer?
- C/C++ Program to the Count set bits in an integer?
- Number of integers with odd number of set bits in C++
- Minimum number using set bits of a given number in C++
- Next higher number with same number of set bits in C++
- Prime Number of Set Bits in Binary Representation in C++
- Count of divisors having more set bits than quotient on dividing N in C++
- Python Program to Count set bits in an integer
- Java Program to Count set bits in an integer
- Print numbers having first and last bits as the only set bits
- Maximum number of contiguous array elements with same number of set bits in C++
- Golang Program to count the set bits in an integer.

Advertisements