Open In App

Binary representation of previous number

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Examples: 

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.

Implementation:

C++





Java





Python3





C#





PHP





Javascript





Output

Binary representation of previous number = 10101

Time Complexity: O(n) where n is number of bits in input.
Auxiliary Space: O(n)

 



Last Updated : 29 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads