-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-binary.cpp
84 lines (69 loc) · 1.55 KB
/
add-binary.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* Copyright (c) 2021, Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <array>
#include <string>
#ifndef BIT
#define BIT(n) (1ULL << (n))
#endif
using namespace std;
// name: add-binary
// url: https://leetcode.com/problems/add-binary
// difficulty: 1
class Solution {
public:
string addBinary(string a, string b) {
// let's force a to always be the longer of the two
if (b.size() > a.size()) {
swap(a, b);
}
// a b c | sum c
// ------------------
// 0 0 0 | 0 0
// 0 0 1 | 1 0
// 0 1 0 | 1 0
// 0 1 1 | 0 1
// 1 0 0 | 1 0
// 1 0 1 | 0 1
// 1 1 0 | 0 1
// 1 1 1 | 1 1
const array<char, 8> sum_lut = {
'0', '1', '1', '0', '1', '0', '0', '1',
};
const array<bool, 8> carry_lut = {
0, 0, 0, 1, 0, 1, 1, 1,
};
bool carry = false;
string sum;
if (a == b && a != "0") {
sum = a;
// simple multiplication by 2 => left shift by 1
sum.push_back('0');
return sum;
}
int i = a.size() - 1;
int j = b.size() - 1;
for (; i >= 0; --i, --j) {
// bit[0] := carry
// bit[1] := b[j]
// bit[2] := a[i]
uint8_t key = carry;
if (j >= 0 && b[j] == '1') {
key |= BIT(1);
}
if (a[i] == '1') {
key |= BIT(2);
}
sum.push_back(sum_lut[key]);
carry = carry_lut[key];
}
if (carry) {
sum.push_back('1');
}
reverse(sum.begin(), sum.end());
return sum;
}
};