diff --git a/LeetCode/problem067_AddBinary.go b/LeetCode/problem067_AddBinary.go new file mode 100644 index 0000000..4a559fb --- /dev/null +++ b/LeetCode/problem067_AddBinary.go @@ -0,0 +1,36 @@ +package leetcode + +// Time complexity: O(n) +// Space complexity: O(n) +func addBinary(a string, b string) string { + i, j := len(a)-1, len(b)-1 + carry := 0 + res := make([]byte, 0, maxInt(len(a), len(b))+1) + + for i >= 0 || j >= 0 || carry > 0 { + sum := carry + if i >= 0 { + sum += int(a[i] - '0') + i-- + } + if j >= 0 { + sum += int(b[j] - '0') + j-- + } + res = append(res, byte(sum%2)+'0') + carry = sum / 2 + } + + for l, r := 0, len(res)-1; l < r; l, r = l+1, r-1 { + res[l], res[r] = res[r], res[l] + } + return string(res) +} + +// Helper function +func maxInt(x, y int) int { + if x > y { + return x + } + return y +} diff --git a/LeetCode/problem067_AddBinary_test.go b/LeetCode/problem067_AddBinary_test.go new file mode 100644 index 0000000..048ea53 --- /dev/null +++ b/LeetCode/problem067_AddBinary_test.go @@ -0,0 +1,25 @@ +package leetcode + +import "testing" + +func TestAddBinary(t *testing.T) { + tests := []struct { + a, b string + expected string + }{ + {"11", "1", "100"}, + {"1010", "1011", "10101"}, + {"0", "0", "0"}, + {"1", "0", "1"}, + {"111", "111", "1110"}, + {"110010", "10111", "1001001"}, + {"1111111111111111", "1", "10000000000000000"}, + } + + for _, tt := range tests { + result := addBinary(tt.a, tt.b) + if result != tt.expected { + t.Errorf("addBinary(%q, %q) = %q; want %q", tt.a, tt.b, result, tt.expected) + } + } +}