Skip to content

Instantly share code, notes, and snippets.

@zhiachong
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhiachong/4e07ce762bd2e22b55ab to your computer and use it in GitHub Desktop.
Save zhiachong/4e07ce762bd2e22b55ab to your computer and use it in GitHub Desktop.
Adding two numbers w/o arithmetic operator
// 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