VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-largest-number-n-set-m-unset-bits/

⇱ Find the largest number with n set and m unset bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the largest number with n set and m unset bits

Last Updated : 31 May, 2022

Given two non-negative numbers n and m. The problem is to find the largest number having n number of set bits and m number of unset bits in its binary representation.
Note : 0 bits before leading 1 (or leftmost 1) in binary representation are counted
Constraints: 1 <= n, 0 <= m, (m+n) <= 31
Examples : 
 

Input : n = 2, m = 2
Output : 12
(12)10 = (1100)2
We can see that in the binary representation of 12 
there are 2 set and 2 unsets bits and it is the largest number. 

Input : n = 4, m = 1
Output : 30


 


Following are the steps:
 

  1. Calculate num = (1 << (n + m)) - 1. This will produce a number num having (n + m) number of bits and all are set.
  2. Now, toggle the last m bits of num and then return the toggled number. Refer this post.


 

Output : 

12

Time Complexity : O(1)

Auxiliary Space: O(1)


For greater values of n and m, you can use long int and long long int datatypes to generate the required number.
 

Comment
Article Tags:
Article Tags: