Program to find 1's complement of a binary number in C++
Written by
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:
- Take binary number input as a string, having a length of
size
. - Initialize
int fail=0
. - Start a loop from
i = 0
toi<size
. - Inside the loop, check if the character at the current index
i
is '0' or '1'. If it is '0', assign '1' to the corresponding index in the complement string. If it is '1', assign '0' to the corresponding index in the complement string. - If the character at the current index
i
is not '0' or '1', print an error message and setfail = 1
. - If
fail
is still 0 after the loop, print the ones complement.
Code:
#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;
}
}
Output
Input a 6 bit binary number: 101101
The original binary number = 101101
Ones complement the number = 010010
Input a 6 bit binary number: 10101
Error! Input the number of assigned bits.