Last active
March 7, 2019 00:53
-
-
Save yphastos/8a2d72c38791c1748de41dcd395fedb8 to your computer and use it in GitHub Desktop.
equal Pair Of Bits
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
// ok: | |
// nota que el codigo es identico a el ejercicio 'different Rightmost Bit', simplemente cambiando la condicion del if | |
function equalPairOfBits($n, $m) { | |
return call_user_func(function($n,$m){ | |
$na = str_split(strrev(str_pad(decbin($n),32,'0',STR_PAD_LEFT))); | |
$ma = str_split(strrev(str_pad(decbin($m),32,'0',STR_PAD_LEFT))); | |
for($i = 0; $i <32; $i++){ | |
if($na[$i] == $ma[$i]){ | |
return pow(2,$i); | |
} | |
} | |
}, $n,$m); ; | |
} | |
// test: no funciona porque se detiene en el primer bit que NO coincida de izq a der. | |
// pero el resultado esperado es el no coincida pero de der a izq. | |
function equalPairOfBits($n, $m) { | |
return call_user_func(function($n,$m){ | |
$na = str_split(($ns = str_pad(decbin($n),32,'0',STR_PAD_LEFT))); | |
$ma = str_split(($ms = str_pad(decbin($m),32,'0',STR_PAD_LEFT))); | |
echo "$ns\n$ms\n"; | |
echo "12345678911234567892123456789312"."\n"; | |
echo "13987654321298765432119876543210"; | |
for($i = 0; $i <32; $i++){ | |
if($na[$i] != $ma[$i]){ | |
echo ",".$i; | |
return pow(2,(32-$i)); | |
} | |
} | |
return 1; | |
}, $n,$m); ; | |
} | |
// other solutions: | |
function equalPairOfBits($n, $m) { | |
return pow(2, strcspn(strrev(sprintf('%032b', $n)) ^ strrev(sprintf('%032b', $m)), "\0")) ; | |
} | |
function equalPairOfBits($n, $m) { | |
return (( $n ^ $m ) + 1) & ( ~ ( $n ^ $m ) ); | |
} | |
function equalPairOfBits($n, $m) { | |
return ~($n ^ $m) & -~($n ^ $m) ; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment