sorry for such a specific question but upon looking at the following algorithm written in Javascript
function c(a) {
if (a < 2) return 2;
if (a > 4096) return 4096;
var b = a & (a - 1);
while (b > 0) {
a++;
b = a & (a - 1)
}
return a
}
I came accross a statement I wasn't sure about. What exactly does var b = a & (a - 1);
actually do? I was under the assumption it assigned A to B and then subtracted 1 from B, however, if that was the case then wouldn't B never reach 0 (or below 0) resulting in an infinite loop? How can this work?
I ask this because I have attempted to adapt the algorithm to PHP but have hit a wall. It works flawlessly in Javascript, so I know for certain that I'm not understanding what is happening. Here is my attempt in PHP:
function c($a) {
if ($a < 2) return 2;
if ($a > 4096) return 4096;
$b = $a
$b = ($b - 1);
while ($b > 0) {
$a++;
$b = $a;
$b -= 1;
}
return $b;
}
I can see clearly why it doesn't work but I'm not sure how to change the algorithm to make it work. More or less, I know that I am not adapting the algorithm properly because I don't understand how it works in Javascript.
Either way, please help me! I don't specifically want someone to work out my problem for me but a hint in the right direction would be really great. :(
Thanks alot.