Skip to content

Instantly share code, notes, and snippets.

@wildlyinaccurate
Created February 7, 2014 08:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wildlyinaccurate/8859257 to your computer and use it in GitHub Desktop.
Save wildlyinaccurate/8859257 to your computer and use it in GitHub Desktop.
Bitwise addition
// Fuck the addition operator. Real programmers work in binary!
function add(a, b) {
// XOR to get the sum of the bits
var sum = a ^ b;
// "Carry" bits are common to both numbers
var carry = (a & b) << 1;
if (sum & carry) {
// Rinse and repeat until there are no leftover bits
return add(sum, carry);
} else {
return sum ^ carry;
}
}
/*
> add(5, 6)
11
> add(5, 10)
15
> add(-1, 40)
39
> add(1, 9)
10
*/
@BitterDone
Copy link

Thank you so much for this - I found you from Google and have been working on this problem for a while. Working through B2B SWE's video:
https://www.youtube.com/watch?v=qq64FrA2UXQ

@ozgursar
Copy link

adding 1234567890 + 1234567890 causes it to return a minus number. What could be the cause?
By the way, 123456789 + 123456789 works just fine.

@wildlyinaccurate
Copy link
Author

@ozgursar this function is only correct for numbers where the sum is equal to or less than 2147483647 (the maximum signed 32-bit integer).

> add(2147483647, 0)
< 2147483647

> add(2147483647, 1)
< -2147483648

@ozgursar
Copy link

@wildlyinaccurate thank you. I tried to split the input numbers into smaller parts to be able to sum larger numbers but it computes incorrectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment