Domanda di colloquio di Meta

Addition of 2 binary numbers.

Risposte di colloquio

Anonimo

31 gen 2018

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()) }

Anonimo

10 giu 2018

func addBinaries(binary1: String, binary2: String) -> Int { let firstNumber = Int(binary1, radix: 2) let secondNumber = Int(binary2, radix: 2) return (firstNumber ?? 0) + (secondNumber ?? 0) }