Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Created November 3, 2017 13:32
Show Gist options
  • Save AdrianFerreyra/db0e4fb221117f5adde1718ae953c77b to your computer and use it in GitHub Desktop.
Save AdrianFerreyra/db0e4fb221117f5adde1718ae953c77b to your computer and use it in GitHub Desktop.
Sum of two binaries, represented through strings.
import Foundation
func sum(_ lhs: String,_ rhs: String, carry: Int = 0) -> String {
guard let lhsLast = lhs.last else {
if rhs.count > 0 {
return rhs
} else {
return carry == 1 ? "1" : ""
}
}
guard let rhsLast = rhs.last else {
if lhs.count > 0 {
return lhs
} else {
return carry == 1 ? "1" : ""
}
}
switch (lhsLast,rhsLast,carry) {
case ("0","0",0): return sum(String(lhs.dropLast()), String(rhs.dropLast()), carry: 0) + "0"
case ("0","0",1): return sum(String(lhs.dropLast()), String(rhs.dropLast()), carry: 0) + "1"
case ("1","0",1),("0","1",1): return sum(String(lhs.dropLast()), String(rhs.dropLast()), carry: 1) + "0"
case ("1","0",0),("0","1",0): return sum(String(lhs.dropLast()), String(rhs.dropLast()), carry: 0) + "1"
case ("1","1",0): return sum(String(lhs.dropLast()), String(rhs.dropLast()), carry: 1) + "0"
case ("1","1",1): return sum(String(lhs.dropLast()), String(rhs.dropLast()), carry: 1) + "1"
default: return ""
}
}
let a = "1100"
let b = "1000"
let sumResult = sum(a,b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment