Skip to content

Instantly share code, notes, and snippets.

@theevo
Created June 11, 2020 15:23
Show Gist options
  • Save theevo/32d4d4f17cbf772fdad3ac2c1ea6fd8f to your computer and use it in GitHub Desktop.
Save theevo/32d4d4f17cbf772fdad3ac2c1ea6fd8f to your computer and use it in GitHub Desktop.
extension String {
var length: Int {
return count
}
subscript (i: Int) -> String {
return self[i ..< i + 1]
}
func substring(fromIndex: Int) -> String {
return self[min(fromIndex, length) ..< length]
}
func substring(toIndex: Int) -> String {
return self[0 ..< max(0, toIndex)]
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
}
class Solution {
func addBinary(_ a: String, _ b: String) -> String {
let long = a.count >= b.count ? a : b
let short = a.count < b.count ? a : b
var sum: String = ""
var j = short.count-1
var carry1 = false
for i in stride(from: long.count-1, through: 0, by: -1) {
if j >= 0 {
// print("\(long[i]) + \(short[j])")
switch carry1 {
case false:
if (long[i] == "0" && short[j] == "1") ||
(long[i] == "1" && short[j] == "0") {
sum = "1" + sum
} else if (long[i] == "0" && short[j] == "0") {
sum = "0" + sum
} else if (long[i] == "1" && short[j] == "1") {
sum = "0" + sum
carry1 = true
}
case true:
if (long[i] == "0" && short[j] == "1") ||
(long[i] == "1" && short[j] == "0") {
sum = "0" + sum
// carry1 = true
} else if (long[i] == "0" && short[j] == "0") {
sum = "1" + sum
carry1 = false
} else if (long[i] == "1" && short[j] == "1") {
sum = "1" + sum
// carry1 = true
}
}
j -= 1
} else {
// the short string has reached the end. only the long string is left
switch carry1 {
case false:
sum = long[i] + sum
case true:
if long[i] == "1" {
sum = "0" + sum
// carry1 = true
} else if long[i] == "0" {
sum = "1" + sum
carry1 = false
}
}
}
}
if carry1 {
sum = "1" + sum
}
return sum
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment