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 simple solution

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

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

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
593
Views Today
Views Today
1
Posted in Algorithm and tagged , .