Bitwise Operations

This is a famous interview question: 'write a routine that adds two positive integers and do it without using mathematic operators'. Turns out you can do this using binary!

Bitwise Operations

Up until now we've been representing binary values as strings so we could see what's going on. It's time now to change that and get into some real binary operations.

All of the logic gates we've been using (AND, XOR, OR, etc) are part of every programming languages as bitwise operators. You've probably seen them before - here they are in JavaScript:

  • & is AND
  • || is OR
  • ^ is XOR

And so on. In this video we dive in head-first and answer a pretty common interview question:

Create a routine that adds two positive integers together without using mathematic operators.

I got asked this once and drew a complete blank as I had no idea and let the interviewer know that. They tried to offer me clues but I was beyond any kind of help, in a completely foreign land. I knew absolutely nothing about binary!

If this is you, buckle up cause here we go!

The Code

Here's the code we'll be cycling on for the video:

const add =function(x,y) {
  //iterate until there is no carry
  let should_carry = null;
  while(should_carry !== 0){
    should_carry = x & y;
    x = x ^ y;
    y = should_carry << 1;
  return x;