-
Notifications
You must be signed in to change notification settings - Fork 0
/
067_AddBinary.js
67 lines (62 loc) · 1.31 KB
/
067_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
// https://leetcode.com/problems/add-binary/#/description
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function (a, b) {
var result = [];
var subLen = a.length - b.length;
if (subLen > 0) {
for (var i = 0; i < subLen; i++) {
b = '0' + b;
}
} else if (subLen < 0) {
subLen = -subLen;
for (var i = 0; i < subLen; i++) {
a = '0' + a;
}
}
var maxLen = a.length - 1;
var carry = false;
for (maxLen; maxLen >= 0; maxLen--) {
var temp = a[maxLen] + b[maxLen];
if (carry) {
switch (temp) {
case '11':
result[maxLen] = '1';
break;
case '10':
case '01':
result[maxLen] = '0';
break;
case '00':
result[maxLen] = '1';
carry = false;
break;
}
} else {
switch (temp) {
case '11':
carry = true;
result[maxLen] = '0';
break;
case '10':
case '01':
result[maxLen] = '1';
break;
case '00':
result[maxLen] = '0';
break;
}
}
}
var str = result.join('');
if (carry) {
str = '1' + str;
}
return str
};
console.log(addBinary('11', '1'));
console.log(addBinary('101', '1'));
console.log(addBinary('1111', '11'));