-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompements.cpp
More file actions
50 lines (46 loc) · 1.06 KB
/
Compements.cpp
File metadata and controls
50 lines (46 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
using namespace std;
void onesComplement(string binary, string &result)
{
int length = binary.length();
for (int i = 0; i < length; i++)
{
if (binary[i] == '0')
result[i] = '1';
else
result[i] = '0';
}
}
void twosComplement(string binary, string &result)
{
int length = binary.length();
onesComplement(binary, result);
int carry = 1;
for (int i = length - 1; i >= 0; i--)
{
if (result[i] == '0' && carry == 1)
{
result[i] = '1';
carry = 0;
}
else if (result[i] == '1' && carry == 1)
{
result[i] = '0';
carry = 1;
}
}
}
int main()
{
string binary, onesComp, twosComp;
cout << "Enter a binary number: ";
cin >> binary;
onesComp = binary;
twosComp = binary;
onesComplement(binary, onesComp);
twosComplement(binary, twosComp);
cout << "1's complement: " << onesComp << endl;
cout << "2's complement: " << twosComp << endl;
return 0;
}