Add Binary Numbers

I love Swift for a couple of reasons of which one is clean and readable code. As an advocate of simple to read code and using functions available with the system I prefer to work with simpler code and one that would be provided by the system.

So let’s look at the problem at hand,

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,

a = "11"
b = "1"
Return "100"

A simple solution

The simplest solution is to add the binary numbers as Ints and then return that back as a binary string.

func addBinary(a:String, b:String) -> String {
    func toInt(binaryString: String) -> Int {
        return strtol(binaryString, nil, 2)
    }
    
    let _a = toInt(binaryString: a)
    let _b = toInt(binaryString: b)
    
    return String(_a + _b, radix: 2)
}

let result = addBinary(a:"11", b:"1")
print(result)

UPDATE:
It is interesting to note that the radix function is available with most of the primitives in Swift, so instead of using the strtol (String To Long) function, we can simply use the swift-ier version as Int(binaryString, radix: 2), so the above code can be changed to

func addBinary(a:String, b:String) -> String {
    guard let _a = Int(a, radix: 2),
        _b = Int(b, radix: 2) else { return "0" }
    
    return String(_a + _b, radix: 2)
}
let result = addBinary(a:"11", b:"1")
print(result)

As a smart developer, you could do some intelligent string manipulation which could be used in any other language. However when using Swift, it makes more sense to use the optimized functions that apple engineers are striving to provide. Benchmarking another solution that seems intelligent and floating on the Interwebs came in slower than the above solution.

Summary

If you want to write something cross-platform, then you can write some interesting algorithms however if you are wanting to use Swift, then it would be recommended to use internal functions as they are a compiled and optimized version. On the Plus side, it is also smaller and easier to read.

Oh and yes, this is something that you could encounter if you were interviewing for Facebook.

Views All Time
Views All Time
3741
Views Today
Views Today
1
Posted in Algorithm and tagged , .