Largest number with binary representation is m 1’s and m-1 0’s in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the largest number with m 1's and m - 1 0's.

Let's see the steps to solve the problem.

  • Initialise two variables bits and result with 2 and 1 respectively.
  • Write a loop that iterates from 1 to n.
    • Update the iterating variable value with pow(2, bits) - 1) * (pow(2, bits - 1).
    • If the iterative variable is less than n, then update the result with i.
    • Increment the bits count.
  • Return resutl.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
long long getTheNumber(long long n) {
   long bits = 2;
   long long result = 1;
   long long i = 1;
   while (i < n) {
      i = (int)(pow(2, bits) - 1) * (pow(2, bits - 1));
      if (i < n) {
         result = i;
      }
      bits++;
   }
   return result;
}
int main() {
   long long n = 654;
   cout << getTheNumber(n) << endl;
   return 0;
}

Output

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

496

Conclusion

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

raja
Published on 09-Apr-2021 17:10:25
Advertisements