Given a binary input that represents binary representation of positive number n, find binary representation of n+1.
The binary input may be and may not fit even in unsigned long long int.
Input : 10011 Output : 10100 Here n = (19)10 = (10011)2 next greater integer = (20)10 = (10100)2 Input : 111011101001111111 Output : 111011101010000000
We store input as string so that large numbers can be handled. We traverse the string from rightmost character and convert all 1s to 0s until we find a 0. Finally convert the found 0 to 1. If we do not find a 0, we append a 1 to overall string.
string nextGreater(num) l = num.length // Find first 0 from right side. While // searching, convert 1s to 0s for i = l-1 to 0 if num[i] == '0' num[i] = '1' break else num[i] = '0' // If there was no 0 if i < 0 num = '1' + num return num
Below is the implementation of above idea.
Binary representation of next number = 10100
Time Complexity : O(n) where n is number of bits in input.
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.
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Binary representation of previous number
- Largest number with binary representation is m 1's and m-1 0's
- Prime Number of Set Bits in Binary Representation | Set 1
- Prime Number of Set Bits in Binary Representation | Set 2
- Check if binary representation of a number is palindrome
- Occurrences of a pattern in binary representation of a number
- Check if binary representation of a given number and its complement are anagram
- Sum of decimal equivalent of all possible pairs of Binary representation of a Number
- Check if actual binary representation of a number is palindrome
- Binary representation of next greater number with same number of 1's and 0's
- Find the occurrence of the given binary pattern in the binary representation of the array elements
- Maximum 0's between two immediate 1's in binary representation
- Maximum distance between two 1's in Binary representation of N
- Count numbers have all 1s together in binary representation