# Write a program to calculate one's and two's complement of a number ?

A binary string will be given to us and we need to print its 1s and 2s complement of that ?

```#include <bits/stdc++.h>
using namespace std;

char flip(char c)
{
if(c == '0')
return '1';
return '0';
}

int main()
{
string bin = "110101";
//	string bin = "1111";
//	string bin = "0000";
//	string bin = "10000";
//	string bin = "10101";
//	string bin = "00001";

int l = bin.length();
int i;

string ones, twos;
ones = twos = "";

//	for ones complement flip every bit
for (i = 0; i < l; i++)
{
ones += flip(bin[i]);
}

//	for two's complement go from right to left in ones complement
//	and if you are getting 1 make them 0 and keep going left
//	when you get first 0 make that 1 and go out of loop

twos = ones;
for (i = l - 1; i >= 0; i--)
{
if (ones[i] == '1')
{
twos[i] = '0';
}
else
{
twos[i] = '1';
break;
}
}
if (i == -1)			//	no break : all are 1  as in 111  or  11111; in such case  add extra 1 in starting
{
twos = '1' + twos;
}

cout << "1's complement: " << ones << endl;
cout << "2's complement: " << twos << endl;
}```

```#include<stdio.h>
#include<string.h>
void main()
{
int i,n,c=0;
char bin[10]="0101",one[10],two[10];
n=strlen(bin);
for(i=0;i<n;i++)
if(bin[i]=='1')
one[i]=0;
else
one[i]=1;
one[i]='\0';
for(i=0;i<n;i++)
printf("One's Compliment:%d",one[i]);
for(i=n-1;i>=0;i--)
{
if(i==n-1)
{
if(one[i]=='1')
{
two[i]=0;
c=1;
}
else
two[i]=1;
}
else
{
if(c==1&&one[i]=='1')
two[i]=0;
else
{

if(c==1&&one[i]=='0')
{
two[i]=1;
c=0;
}
else two[i]=one[i];
}

}
}
two[n]='\0';
for(i=0;i<n;i++)
printf("Two's compliment:%d",two[i]);
}
```