|
@@ -0,0 +1,59 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import (
|
|
|
+ "strings"
|
|
|
+ "fmt"
|
|
|
+ "math"
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+// add binary
|
|
|
+func minInt(x, y int) int {
|
|
|
+ if x < y { return x }
|
|
|
+ return y
|
|
|
+}
|
|
|
+
|
|
|
+const one, zero = byte('1'), byte('0')
|
|
|
+
|
|
|
+func add3Bi(x, y, z byte) (sum, remain byte) {
|
|
|
+ switch x + y + z - 3 * zero {
|
|
|
+ case 0: return zero, zero
|
|
|
+ case 1: return one, zero
|
|
|
+ case 2: return zero, one
|
|
|
+ case 3: return one, one
|
|
|
+ default: return
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+func reverseStr(s string) string {
|
|
|
+ runes := []rune(s)
|
|
|
+ for from, to := 0, len(s) - 1; from < to; from, to = from + 1, to - 1 {
|
|
|
+ runes[from], runes[to] = runes[to], runes[from]
|
|
|
+ }
|
|
|
+ return string(runes)
|
|
|
+}
|
|
|
+
|
|
|
+func addBinary(a string, b string) string {
|
|
|
+ la, lb := len(a) - 1, len(b) - 1
|
|
|
+ sum, remain := zero, zero
|
|
|
+ res := make([]rune, 0)
|
|
|
+ for i := 0; i <= minInt(la, lb); i++ {
|
|
|
+ sum, remain = add3Bi(a[la - i], b[lb - i], remain)
|
|
|
+ res = append(res, rune(sum))
|
|
|
+ }
|
|
|
+ lc := 0
|
|
|
+ var c string
|
|
|
+ if la < lb {
|
|
|
+ c = b
|
|
|
+ lc = lb
|
|
|
+ } else {
|
|
|
+ c = a
|
|
|
+ lc = la
|
|
|
+ }
|
|
|
+ for i := minInt(la, lb) + 1; i <= lc; i++ {
|
|
|
+ sum, remain = add3Bi(zero, c[lc - i], remain)
|
|
|
+ res = append(res, rune(sum))
|
|
|
+ }
|
|
|
+ if remain == one { res = append(res, rune(one)) }
|
|
|
+ return reverseStr(string(res))
|
|
|
+}
|