-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution67.cpp
More file actions
82 lines (75 loc) · 1.8 KB
/
solution67.cpp
File metadata and controls
82 lines (75 loc) · 1.8 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#pragma once
#include "solutions.hpp"
string Solutions::addBinary(string a, string b) {
string res = "";
int i = 0, j = 0;
bool cflag = false; // Carry Flag
for (; i < a.length() && j < b.length(); i++, j++) {
// list the carry case
if (cflag == true) {
if (a[a.length() - 1 - i] == '0' && b[b.length() - 1 - j] == '0') {
cflag = false;
res = '1' + res;
}
if ((a[a.length() - 1 - i] == '0' && b[b.length() - 1 - j] == '1') || (a[a.length() - 1 - i] == '1' && b[b.length() - 1 - j] == '0')) {
cflag = true;
res = '0' + res;
}
if (a[a.length() - 1 - i] == '1' && b[b.length() - 1 - j] == '1') {
cflag = true;
res = '1' + res;
}
} else {
if (a[a.length() - 1 - i] == '0' && b[b.length() - 1 - j] == '0') {
cflag = false;
res = '0' + res;
}
if ((a[a.length() - 1 - i] == '0' && b[b.length() - 1 - j] == '1') || (a[a.length() - 1 - i] == '1' && b[b.length() - 1 - j] == '0')) {
cflag = false;
res = '1' + res;
}
if (a[a.length() - 1 - i] == '1' && b[b.length() - 1 - j] == '1') {
cflag = true;
res = '0' + res;
}
}
}
// deal with the extra binary char in b
if (i == a.length()) {
while (j < b.length()) {
if (cflag == true) {
if (b[b.length() - 1 - j] == '1') {
cflag = true;
res = '0' + res;
} else {
cflag = false;
res = '1' + res;
}
} else {
res = b[b.length() - 1 - j] + res;
}
j++;
}
}
// deal with the extra binary char in a
if (j == b.length()) {
while (i < a.length()) {
if (cflag == true) {
if (a[a.length() - 1 - i] == '1') {
cflag = true;
res = '0' + res;
} else {
cflag = false;
res = '1' + res;
}
} else {
res = a[a.length() - 1 - i] + res;
}
i++;
}
}
if (cflag == true) {
res = '1' + res;
}
return res;
}