visit
There are multiple methods to subtract binary numbers. Some of them are as follows -
1 0 1 0
- 1 0 1
1 0 1 0
- 1 0 1
1
1 0 1 0
- 1 0 1
1 0 1 0
- 1 0 1
Take two numbers 110101(53) and 100101(37).
Take two numbers 10101(21) and 00111(7). Calculating the two’s complement of the subtrahend.
1 0 1 0 1
+ 1 1 0 0 1
1 0 1 1 1 0
We get to carry 1 so we discard it and the final answer comes to 01110(14).
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
// Program to subtract two binary numbers
void Subtract(int n, int a[], int b[])
{
// 1's Complement of the subtrahend
for(int i = 0; i < n; i++)
{
//Replace 1 by 0
if(b[i] == 1)
{
b[i] = 0;
}
//Replace 0 by 1
else
{
b[i] = 1;
}
}
//Add 1 at end to get 2's Complement of the subtrahend
for(int i = n - 1; i >= 0; i--)
{
if(b[i] == 0)
{
b[i] = 1;
break;
}
else
{
b[i] = 0;
}
}
// Represents carry
int t = 0;
for(int i = n - 1; i >= 0; i--)
{
// Add a, b and carry
a[i] = a[i] + b[i] + t;
// If a[i] is 2
if(a[i] == 2)
{
a[i] = 0;
t = 1;
}
// If a[i] is 3
else if(a[i] == 3)
{
a[i] = 1;
t = 1;
}
else
t = 0;
}
cout << endl;
// If carry is generated
// discard the carry
if(t==1)
{
// print the result
for(int i = 0; i < n; i++)
{
// Print the result
cout<<a[i];
}
}
// if carry is not generated
else
{
// Calculate 2's Complement
// of the obtained result
for(int i = 0; i < n; i++)
{
if(a[i] == 1)
a[i] = 0;
else
a[i] = 1;
}
for(int i = n - 1; i >= 0; i--)
{
if(a[i] == 0)
{
a[i] = 1;
break;
}
else
a[i] = 0;
}
// Add -ve sign to represent
cout << "-";
// -ve result
// Print the resultant array
for(int i = 0; i < n; i++)
{
cout << a[i];
}
}
}
int main() // Main function
{
int n;
n = 5;
int a[] = {1, 0, 1, 0, 1},
b[] = {0, 0, 1, 1, 1};
Subtract(n,a,b);
return 0;
}
Output:
01110
Time complexity - O(nlogn)
Space complexity - O(1)
In simple subtraction, we borrow a bit from the next higher significant bit.
In 1’s complement, we perform the 1’s complement of the subtrahend and add it to the minuend. If there is a carry add it to the last bit else take 1’s complement of the result.
In the case of 2’s complement subtraction, take the two’s complement of the subtrahend and add it to the minuend. If there is a carry discard it, else take two’s complement of the result which will result in a negative answer**.**