RUN


Problem –  Binary Number as a string, we have to print its 1’s complement.

1’s complement of a binary number is another binary number obtained by transforming all the 0 bit to 1 and the 1 bit to 0.

Example:

Input: 101010                   

One’s complement the number: 010101

Algorithm:

  1. Take binary number input as string having length say size.
  2. Initialize int fail=0.
  3. Start loop from i=0 to i<size
       if binary[i]==1then comp[i]=0

      else if binary[i]==0

    then comp[i]=1

      else

    print “error! Enter binary number of assigned size”

    fail=1

    break

  4. Put null character in the string complement

    comp[size] = ‘\0’

  5. If fail ==0 then print the ones complement.

Code:

//Program to find one's complement of a binary number

#include <iostream>
#define size 6
using namespace std;

int main(){

     int i, fail = 0;

     char binary[size + 1], comp[size + 1];

   cout << " Input a "<<size <<" bit binary number: ";

     cin >> binary;

     for (i = 0; i < size; i++) {

         if (binary[i] == '1') {

             comp[i] = '0';

         }

         else if (binary[i] == '0') {

             comp[i] = '1';

         } else {
             cout << "Error! Input the number of assigned bits." << endl;

             fail = 1;

             break;

         }

     }

     comp[size] = '\0';

     if (fail == 0){

         cout << "The original binary number = " << binary << endl;

         cout << "Ones complement the number = " << comp << endl;

     }

}

Report Error/ Suggestion

Related Posts:




CopyRight © 2020

CopyRight © 2020