Last active
August 29, 2015 14:03
-
-
Save zhiachong/4e07ce762bd2e22b55ab to your computer and use it in GitHub Desktop.
Adding two numbers w/o arithmetic operator
This file contains 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
// my initial version | |
function add($x, $y) | |
{ | |
$result = 0; | |
$i = 0; // the first bit to look at | |
$max = max($x, $y); | |
$msb = log($max, 2); // get the most signicant bit | |
$carry = 0; | |
while ($i <= $msb || $carry) | |
{ | |
$xBit = (1 << $i) & $x; // get the bit we want to compare from x | |
$yBit = (1 << $i) & $y; // get the bit we want to compare from y | |
$xor = $xBit ^ $yBit; | |
$oldXor = $xor; | |
$xor = $xor ^ $carry; | |
if ($oldXor == 0 || $xor == 0) | |
{ | |
$carry = 0; | |
if ($xBit & $yBit || $oldXor & $carry) | |
{ | |
$carry = 1 << ($i+1); | |
} | |
} | |
$result = $xor | $result; // set the bit for the result | |
$i++; | |
} | |
return $result; | |
} | |
// Optimized version | |
function add($x, $y) | |
{ | |
if ($y==0) return $x; | |
$sum = $x ^ $y; | |
$carry = ($x & $y) << 1; | |
return add($sum, $carry); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment