Given a binary input that represents binary representation of positive number n, find binary representation of smallest number greater than n with same number of 1’s and 0’s as in binary representation of n. If no such number can be formed, print “no greater number”. The binary input may be and may not fit even in unsigned long long int.
Input : 10010
Output : 10100
Here n = (18)10 = (10010)2next greater = (20)10 = (10100)2
Binary representation of 20 contains same number of
1's and 0's as in 18.
Input : 111000011100111110
Output : 111000011101001111
Console.WriteLine("Binary representation of next greater number = "
// This code is contributed by 29AjayKumar
// in a binary string.
// Function to find the next greater number
// with same number of 1's and 0's
let l = bnum.length;
for(i = l - 2; i >= 1; i--)
// Locate first 'i' from end such that
// bnum[i]=='0' and bnum[i+1]=='1'
// swap these value and break;
if(bnum[i] == '0'&&
bnum[i + 1] == '1')
let ch = bnum[i];
bnum[i] = bnum[i+1];
bnum[i+1] = ch;
// If no swapping performed
if(i == 0)
document.write("no greater number<br>");
// Since we want the smallest next value,
// shift all 1's at the end in the binary
// substring starting from index 'i+2'
let j = i + 2, k = l - 1;
while(j < k)
if(bnum[j] == '1' && bnum[k] == '0')
let ch = bnum[j];
bnum[j] = bnum[k];
bnum[k] = ch;
// Special case while swapping if '0'
// occurs then break
else if (bnum[i] == '0')
// Required next greater number
// Driver code
let bnum = "10010".split("");
document.write("Binary representation of next "+
"greater number = "+
// This code is contributed by rag2127
Binary representation of next greater number = 10100
Time Complexity : O(n) where n is number of bits in input. Auxiliary Space: O(1)
This article is contributed by Aarti_Rathi and Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...