Binary representation of next 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 next number i.e. the number that is resulted after adding one to 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 14 is 1110.

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 addition. Let's see what happens when 1 is added to 0 or 1 in binary form.

0 + 1 = 1 

1 + 1 = 10

Example

Let's see an example on how to solve the above problem,

Input: 010010111
Output: 010011000
Explanation : (010010111)2 is the binary representation of 152 and the next number will be 153 
whose binary representation is (010011000)2. We will use binary addition here and add binary (1)2 
to the binary representation of the number.

From the above example we can see that on adding binary 1 to the number all the ones starting from right are converted to 0, until the first 0 is encountered and this 0 is flipped to 1. now let's create an algorithm for this logic.

Algorithm

Step 1 : Start right to left i.e n-1 to 0
Step 2 : If 0 is encountered, change it 1 and break
Step 3 : If one is encounter change it to 0.
Step 4 : When no zero is encountered, add 1 to the start of the array.
Step 5 : Print the array.

Example

Now, let's see the code implementation of this algorithm.

#include <bits/stdc++.h>
using namespace std;
string nextBinary(string num) {
   int l = num.size();
   int flag = 0 ;
   for (int i=l-1; i>=0; i--) {
      if (num.at(i) == '0') {
         num.at(i) = '1';
         flag = 1;
         break;
      } else
         num.at(i) = '0';
   }
   if (flag < 0)
      num = "1" + num;
   return num;
}
int main() {
   string number = "0111010111";
   cout<<"The Binary representation of the number is "<<number<<endl;
   cout<<"Binary representation of next number is "<<nextBinary(number);
   return 0;
}

Output

The Binary representation of the number is 0111010111
Binary representation of next number is 0111011000

Updated on: 22-Nov-2019

360 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements