Skip to content

Instantly share code, notes, and snippets.

@theodesp
Last active September 17, 2019 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theodesp/04297affb741334584157ff3b85a02f6 to your computer and use it in GitHub Desktop.
Save theodesp/04297affb741334584157ff3b85a02f6 to your computer and use it in GitHub Desktop.
Add 2 Binary Strings #go
/*
Observation: We start from the last char for each string. As long as we have not reached the beginning we compare the chars. The math is
1 + 1 = 0 (curry = 1)
1 + 0 = 0 + 1 = 1 (curry = 0)
1 + 1 = 1 (curry = 1) if curry = 1
1 + 0 = 0 + 1 = 0 (curry = 1) if curry = 1
If we have a curry in the end we prepend the 1
Note: Adding 2 mumbers is similar. We have to calculate:
sum := carry + x + y
carry = sum / 10
val = sum % 10
*/
func AddBinary(a string, b string) string {
res := ""
curry := 0
l1 := len(a) - 1
l2 := len(b) - 1
for l1 >= 0 || l2 >= 0 {
var left = 0
var right = 0
if l1 >= 0 {
if rune(a[l1]) == '1' {
left = 1
}
l1 -= 1
}
if l2 >= 0 {
if rune(b[l2]) == '1' {
right = 1
}
l2 -= 1
}
added := curry + left + right
switch added {
case 0:
res = "0" + res
curry = 0
case 1:
res = "1" + res
curry = 0
case 2:
res = "0" + res
curry = 1
case 3:
res = "1" + res
curry = 1
}
}
if curry == 1 {
res = "1" + res
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment