Given a binary input that represents binary representation of positive number n, find binary representation of n-1. It may be assumed that input binary number is greater than 0.
The binary input may or may not fit even in unsigned long long int.
Input : 10110 Output : 10101 Here n = (22)10 = (10110)2 Previous number = (21)10 = (10101)2 Input : 11000011111000000 Output : 11000011110111111
We store input as string so that large numbers can be handled. We traverse the string from rightmost character and convert all 0’s to 1’s until we find a 1. Finally convert the found 1 to 0. The number so formed after this process is the required number. If input is “1”, then previous number will be “0”. If only the first character in the entire string is ‘1’, then we discard this character and change all the 0’s to 1’s.
Binary representation of previous number = 10101
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 firstname.lastname@example.org. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the occurrence of the given binary pattern in the binary representation of the array elements
- Binary representation of next greater number with same number of 1's and 0's
- Number of leading zeros in binary representation of a given number
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Count number of trailing zeros in Binary representation of a number using Bitset
- Binary representation of a given number
- Check if binary representation of a number is palindrome
- Binary representation of next number
- Check if binary representation of a given number and its complement are anagram
- Find the n-th number whose binary representation is a palindrome
- Prime Number of Set Bits in Binary Representation | Set 2
- Largest number with binary representation is m 1's and m-1 0's
- Check if actual binary representation of a number is palindrome
- Prime Number of Set Bits in Binary Representation | Set 1
- Length of longest consecutive zeroes in the binary representation of a number.
- Sum of decimal equivalent of all possible pairs of Binary representation of a Number
- Next greater number than N with exactly one bit different in binary representation of N
- Number of mismatching bits in the binary representation of two integers
- Find consecutive 1s of length >= n in binary representation of a number
- Occurrences of a pattern in binary representation of a number