forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddBinary.js
102 lines (90 loc) · 2.41 KB
/
AddBinary.js
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Given two binary strings, return their sum (also a binary string).
*
* For example,
* a = "11"
* b = "1"
* Return "100".
*
* Accepted.
*/
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
let addBinary = function (a, b) {
if (a == null || b == null) {
return "";
}
if (a.length === 0) {
return b;
}
if (b.length === 0) {
return a;
}
let flag = false; // if it needs to plus one
let longer = a.length >= b.length ? a : b;
let shorter = a.length < b.length ? a : b;
let builder = "";
for (let i = longer.length - 1, j = shorter.length - 1; i >= 0; i--, j--) {
if (j < 0) {
if (longer.charAt(i) === "1") {
if (flag) {
builder = builder.concat("0");
} else {
builder = builder.concat("1");
}
} else { // l == "0"
if (flag) {
builder = builder.concat("1");
flag = false;
} else {
builder = builder.concat("0");
}
}
} else {
if ((longer.charAt(i) === "1" && shorter.charAt(j) === "1")) {
if (flag) {
builder = builder.concat("1");
} else {
builder = builder.concat("0");
}
flag = true;
} else if (longer.charAt(i) === "0" && shorter.charAt(j) === "0") {
if (flag) {
builder = builder.concat("1");
} else {
builder = builder.concat("0");
}
flag = false;
} else { // (l == "1" && s == "0") || (l == "0" && s == "1")
if (flag) {
builder = builder.concat("0");
flag = true;
} else {
builder = builder.concat("1");
}
}
}
}
if (flag) {
builder = builder.concat("1");
}
return builder.split('').reverse().join('');
};
if (addBinary("0", "0") === "0") {
console.log("pass")
} else {
console.error("failed")
}
if (addBinary("11", "1") === "100") {
console.log("pass")
} else {
console.error("failed")
}
if (addBinary("101", "101") === "1010") {
console.log("pass")
} else {
console.error("failed")
}