Skip to content

Instantly share code, notes, and snippets.

@tairov
Created February 14, 2014 06:35
Show Gist options
  • Save tairov/8996692 to your computer and use it in GitHub Desktop.
Save tairov/8996692 to your computer and use it in GitHub Desktop.
binadd, php
function binadd($a, $b) {
$n = strlen($a);
$m = strlen($b);
$max = max($n, $m);
$sum = [];
$r = 0;
for ($i = 0; $i < $max; $i++) {
$s = ($n > $i ? $a{$i} : 0) + ($m > $i ? $b{$i} : 0) + $r; $r = 0;
$sum[] = $s & 1 ? '1' : '0';
if ($s > 1) {
$r = 1;
}
}
if ($r) {
$sum[] = '1';
}
return join('', $sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment