
- 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 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 Articles
- 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++
- An object travels $20\ m$ in $5\ s$ and then another $40\ m$ in $5\ s$. What is the average speed of the object?$6\ m/s$$0\ m/s$$12\ m/s$$2\ m/s$
- Count subarrays with equal number of 1’s and 0’s in C++
- 1’s and 2’s complement of a Binary Number?
- 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++
- C++ Largest Subtree having Equal No of 1's and 0's
- Find longest sequence of 1’s in binary representation with one flip in C++
- The correct symbol to represent the speed of an object is$(a)$. $5\ m/s$$(b)$. $5\ mp$$(c)$. $5\ m/s^{-1}$$(d)$. $5\ s/m$
- Construct DFA of alternate 0’s and 1’s
- Count subarrays consisting of only 0’s and only 1’s in a binary array in C++
- Python program to find the length of the largest consecutive 1's in Binary Representation of a given string.
- A bus increases its speed from $36\ km/h$ to $72\ km/h$ in $10\ seconds$. Its acceleration is:(a) $5\ m/s^2$(b) $2\ m/s^2$(c) $3.6\ m/s^2$(d) $1\ m/s^2$
- Find the number of integers from 1 to n which contains digits 0’s and 1’s only in C++

Advertisements