Binary representation of previous number in C++


In this problem, we are given the binary representation of a number and we have to find the binary representation of the previous number i.e. the number that is resulted after subtracting one from the given number.

Binary representation of a number is changing the base of the number to base 2 and representing the number using only 0 or 1.

For example, Binary representation of 23 is 10111.

So, here we would be given a number, let's say n in binary form. And we have to find the binary representation of n-1.

To solve this problem, we need to know the basics of binary subtraction. let's see what happens when 1 is subtracted from 0 or 1 in binary form.0 - 1 = 1 + 1 carry from next bit. 1 - 1 = 0.

Let's take an example to understand the problem better,

Input : 101101100
Output : 101101011
Explanation : (101101100)2 Is the binary representation of 364. The number preceding it is 363 whose
binary representation is (101101011)2 . we have used binary subtraction here and subtracted (1)2 
from the binary representation of the number to yield the result .

Let's see the logic behind this program and then we will design an algorithm based on our logic. Here we need to subtract one from the number’s binary representation. for this, we will start from the right and flip all zeros to 1 until, 1 is encountered. When 1 is encountered, we will flip the 1 to 0 and return the final result.

Algorithm

Step 1 : Start right to left i.e n-1 to 0.
Step 2 : If 1 is encounter change it to 0 and break.
Step 3 : If 0 is encountered, change it 1.
Step 4 : Print the array.

Example

Program implementation of the above algorithm −

#include <bits/stdc++.h>
using namespace std;
string previousNumber(string num) {
   int n = num.size();
   if (num.compare("1") == 0)
      return "0";
      int i;
   for (i = n - 1; i >= 0; i--) {
      if (num.at(i) == '1') {
         num.at(i) = '0';
         break;
      } else
      num.at(i) = '1';
   }
   if (i == 0)
      return num.substr(1, n - 1);
      return num;
}
int main() {
   string number = "1011011000";
   cout<<"the Binary representation of the number is "<<number<<endl;
   cout<<"Binary representation of previous number is "<<previousNumber(number);
   return 0;
}

Output

The Binary representation of the number is 1011011000
Binary representation of previous number is 1011010111

Updated on: 09-Jul-2020

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements