My swift AC solution


  • 0
    Z
        func addBinary(_ a: String, _ b: String) -> String {
            var aA = Array(a.characters.map{String($0)})
            var bA = Array(b.characters.map{String($0)})
            if aA.count == 0 || bA.count == 0 {
                return a + b
            }
            var aC = aA.count - 1
            var bC = bA.count - 1
            var carry = 0
            var result = ""
            while aC > -1 || bC > -1 || carry == 1 {
                let aBit = aC > -1 ? aA[aC] : "0"
                let bBit = bC > -1 ? bA[bC] : "0"
                var tempResult = Int(aBit)! ^ Int(bBit)! ^ carry
                carry = (Int(aBit)! + Int(bBit)! + carry) >= 2 ? 1 : 0
                result = "\(tempResult)" + result
                aC -= 1
                bC -= 1
            }
            return result
                           
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.