

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Largest number with binary representation is m 1’s and m-1 0’s in C++
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.
#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.
- Related Questions & Answers
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Maximum 0’s between two immediate 1’s in binary representation in C++
- C++ Largest Subtree having Equal No of 1's and 0's
- Count subarrays with equal number of 1’s and 0’s in C++
- 1’s and 2’s complement of a Binary Number?
- Construct DFA of alternate 0’s and 1’s
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- Find longest sequence of 1’s in binary representation with one flip in C++
- Construct PDA for L = {0n1m2(n+m) | m,n >=1}
- Find the number of integers from 1 to n which contains digits 0’s and 1’s only in C++
- Construct DPDA for anbmc(n+m) n,m≥1 in TOC
- Sort an arrays of 0’s, 1’s and 2’s using C++
- Sort an arrays of 0’s, 1’s and 2’s using Java
- Segregate 0’s and 1’s in an array list using Python?
Advertisements