Skip to content

F# adder

February 9, 2013

This is a quite popular coding interview question: “Add two numbers without using arithmetic operators“. Solving it assumes candidate’s understanding (or just re-inventing) of how summation was implemented in early days of computer electronics – see how half-adder performs addition of two bits using XOR, AND, and SHIFT. F# one-liner implementing the same approach for adding two integers using just bit manipulations looks elegant enough to deserve a post:

let rec sum n = function 0 -> n | _ as n' -> sum (n^^^n') ((n&&&n')<<<1)

Just beautiful!


From → F#

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: