Last active
August 29, 2015 14:10
-
-
Save nat-n/d40ba7fe1418889c1cd5 to your computer and use it in GitHub Desktop.
Implementing naive integer addition from bitwise operators in javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function add(a,b){ | |
var x, o; | |
do { | |
x = a & b; | |
o = a | b; | |
a = o ^ x; | |
b = x << 1; | |
} while (x) | |
return o; | |
} | |
var testCases = [ | |
[86, 53], | |
[45, 236], | |
[1, 127], | |
[-82341, 1223453], | |
[0, 1223453], | |
[Math.pow(2,30), Math.pow(2,10)], | |
[Math.pow(2,30), Math.pow(2,12)], | |
[Math.pow(2,31), 1], | |
[Math.pow(2,32), 0] | |
]; | |
testCases.forEach(function(testCase){ | |
var result = add(testCase[0], testCase[1]), | |
expected = testCase[0] + testCase[1]; | |
if (result === expected) { | |
console.log('OK'); | |
} else { | |
console.log('! expected', testCase[0], '+', testCase[1], 'to equal', expected, 'but got', result); | |
} | |
}); | |
/* Output | |
OK | |
OK | |
OK | |
OK | |
OK | |
OK | |
OK | |
! expected 2147483648 + 1 to equal 2147483649 but got -2147483647 | |
! expected 4294967296 + 0 to equal 4294967296 but got 0 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment