- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- C/C++ Program for nth Catalan Number?
- C Program to Check if all digits of a number divide it
- Concatenate a string given number of times in C++ programming
- Superperfect Number in C programming
- HTML DOM Input Number value Property
- HTML DOM Input Number type Property
- How to find the number of days in a month of a particular year in Java?
- Number of elements a particular tag contains in JavaScript?
- Print first k digits of 1/n where n is a positive integer in C Program
- Print multiples of Unit Digit of Given Number in C Program
- C/C++ Programming to Count trailing zeroes in factorial of a number?
- C++ Programming for Smallest K digit number divisible by X?
- To find sum of even factors of a number in C++ Program?
- Generating random number list in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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,

#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; }

The number is 3452 The greatest integer smaller than the number is : 3448

Advertisements