-
Notifications
You must be signed in to change notification settings - Fork 20
/
AddBinary.kt
executable file
·83 lines (76 loc) · 2.14 KB
/
AddBinary.kt
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
/**
* Given two binary strings, return their sum (also a binary string).
*
* For example,
* a = "11"
* b = "1"
* Return "100".
*
* Accepted.
*/
class AddBinary {
fun addBinary(a: String?, b: String?): String {
if (a == null || b == null) {
return ""
}
if (a.isEmpty()) {
return b
}
if (b.isEmpty()) {
return a
}
var flag = false // if it needs to plus one
val longer = if (a.length >= b.length) a else b
val shorter = if (a.length < b.length) a else b
val sb = StringBuilder(longer.length + 1)
var i = longer.length - 1
var j = shorter.length - 1
while (i >= 0) {
if (j < 0) {
if (longer[i] == '1') {
if (flag) {
sb.append('0')
} else {
sb.append('1')
}
} else { // l == '0'
if (flag) {
sb.append('1')
flag = false
} else {
sb.append('0')
}
}
} else {
if (longer[i] == '1' && shorter[j] == '1') {
if (flag) {
sb.append('1')
} else {
sb.append('0')
}
flag = true
} else if (longer[i] == '0' && shorter[j] == '0') {
if (flag) {
sb.append('1')
} else {
sb.append('0')
}
flag = false
} else { // (l == '1' && s == '0') || (l == '0' && s == '1')
if (flag) {
sb.append('0')
flag = true
} else {
sb.append('1')
}
}
}
i--
j--
}
if (flag) {
sb.append('1')
}
return sb.reverse().toString()
}
}