Addition of 2 binary numbers.
Utilisateur anonyme
func sumBinaries(_ lhs: String, _ rhs: String) -> String { var result: [Character] = [] var carry = 0 let count = lhs.count >= rhs.count ? lhs.count : rhs.count for i in 1 ..< count + 1 { var num1 = 0 var num2 = 0 if i <= lhs.count { let iLeft = lhs.index(lhs.endIndex, offsetBy: -i) if let intLeft = Int(String(lhs[iLeft])) { num1 = intLeft } } if i <= rhs.count { let iRight = rhs.index(rhs.endIndex, offsetBy: -i) if let intRight = Int(String(rhs[iRight])) { num2 = intRight } } let sum = num1 + num2 + carry print("\(num1) + \(num2) + \(carry) = \(sum)") if sum < 2 { carry = 0 result.append(Character("\(sum)")) } else if sum == 2 { carry = 1 result.append("0") } else { carry = 1 result.append("1") } } if carry == 1 { result.append("1") } return String(result.reversed()) }