-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy path1s_and_2s_complement.cpp
More file actions
63 lines (55 loc) · 1.18 KB
/
1s_and_2s_complement.cpp
File metadata and controls
63 lines (55 loc) · 1.18 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
51
52
53
54
55
56
57
58
59
60
61
62
63
/*** 1s complement and 2s complement ***/
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string bin, temp, ones, twos;
int len;
cout << "Enter a valid binary number: ";
cin >> bin;
len = bin.length();
int count = 0;
while (count != len)
{
if (bin[count] != '1' && bin[count] != '0')
{
cout << "Invalid binary number." << endl;
main();
}
count += 1;
}
// 1's complement
for (int i = 0; i < len; i++)
{
if (bin[i] == '1')
{
bin[i] = '0';
}
else
{
bin[i] = '1';
}
}
ones = bin;
temp = ones;
bin = temp;
// 2's complement
int carry = 1;
for (int i = len - 1; i >= 0; i--)
{
if (bin[i] == '1' && carry == 1)
{
bin[i] = '0';
}
else if (bin[i] == '0' && carry == 1)
{
bin[i] = '1';
carry = 0;
}
}
twos = bin;
cout << "The 1s complement of the entered number is: " << ones << endl;
cout << "The 2s complement of the entered number is: " << twos << endl;
return 0;
}