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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Binary representation of next number
- Binary representation of a given number
- Count number of trailing zeros in Binary representation of a number using Bitset
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Next greater number than N with exactly one bit different in binary representation of N
- Largest number with binary representation is m 1's and m-1 0's
- Number of leading zeros in binary representation of a given number
- Prime Number of Set Bits in Binary Representation | Set 1
- Occurrences of a pattern in binary representation of a number
- Check if binary representation of a number is palindrome
- Prime Number of Set Bits in Binary Representation | Set 2
- Find the n-th number whose binary representation is a palindrome
- Find the number obtained after concatenation of binary representation of M and N
- Check if binary representation of a given number and its complement are anagram
- C program to count zeros and ones in binary representation of a number
- Check if actual binary representation of a number is palindrome
- Number of mismatching bits in the binary representation of two integers
- Sum of decimal equivalent of all possible pairs of Binary representation of a Number
- Find consecutive 1s of length >= n in binary representation of a number
- Binary representation of next greater number with same number of 1's and 0's