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
Contraints: 1 <= n, 0 <= m, (m+n) <= 31
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:
- Calculate num = (1 << (n + m)) – 1. This will produce a number num having (n + m) number of bits and all are set.
- Now, toggle the last m bits of num and then return the toggled number. Refer this post.
For greater values of n and m, you can use long int and long long int datatypes to generate the required number.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Program to find whether a no is power of two
- Write an Efficient Method to Check if a Number is Multiple of 3
- Program to find parity
- Find the Number Occurring Odd Number of Times
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Find the two non-repeating elements in an array of repeating elements
- Rotate bits of a number
- Compute modulus division by a power-of-2-number
- Find whether a given number is a power of 4 or not
- Add 1 to a given number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
Improved By : vt_m