-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum of BCDs.cpp
67 lines (55 loc) · 1 KB
/
sum of BCDs.cpp
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
#include <iostream>
using namespace std;
string intToS(int n);
int sToInt(string n);
int BCDToInt(string n);
string intToBCD(int n);
string sumBCD(string a, string b);
int main() {
string a, b;
cin >> a >> b;
cout << sumBCD(a, b);
}
string intToS(int n) { // 3 -> 0011
string result(4, '0');
for (int digit = 3; digit >= 0; --digit) {
result[digit] = (n % 2) + '0';
n /= 2;
}
return result;
}
int sToInt(string n) {
int result = 0;
for (char digit: n) {
result *= 2;
result += digit - '0';
}
return result;
}
int BCDToInt(string n) {
string digits;
int result = 0;
for (char digit: n) {
digits += digit;
if (digits.length() == 4) {
result *= 10;
result += sToInt(digits);
digits = "";
}
}
return result;
}
string intToBCD(int n) {
string result;
for (; n > 0; n /= 10) {
string cpy = result;
result = intToS(n % 10);
result += cpy;
}
return result;
}
string sumBCD(string a, string b) {
int a_ = BCDToInt(a), b_ = BCDToInt(b);
a_ += b_;
return intToBCD(a_);
}