-
Notifications
You must be signed in to change notification settings - Fork 130
/
Add Binary.js
78 lines (63 loc) · 1.41 KB
/
Add Binary.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
/**
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
var lenA = a.length,
lenB = b.length,
overFlow = 0,
charA,
charB,
result = '',
curVal,
i,
j;
for (i = lenA - 1, j = lenB - 1; i >= 0 && j >= 0; i--, j --) {
charA = parseInt(a.charAt(i));
charB = parseInt(b.charAt(j));
curVal = charA + charB + overFlow;
if (curVal > 1) {
curVal = curVal - 2;
overFlow = 1;
} else {
overFlow = 0;
}
result = curVal + result;
}
while (i >= 0) {
charA = parseInt(a.charAt(i));
curVal = charA + overFlow;
if (curVal > 1) {
curVal = curVal - 2;
overFlow = 1;
} else {
overFlow = 0;
}
result = curVal + result;
i--;
}
while (j >= 0) {
charB = parseInt(b.charAt(j));
curVal = charB + overFlow;
if (curVal > 1) {
curVal = curVal - 2;
overFlow = 1;
} else {
overFlow = 0;
}
result = curVal + result;
j--;
}
if (overFlow === 1) {
result = '1' + result;
}
return result;
};