How to write 4 different functions that check if a number is a power of 2 in PHP

1 Answer

0 votes
// Method A: Bit-counting
function isPowerOfTwoA(int $x): bool {
    if ($x <= 0) return false;
    return substr_count(decbin($x), "1") === 1;
}

// Method B: Bitwise trick
function isPowerOfTwoB(int $x): bool {
    return $x > 0 && ($x & ($x - 1)) === 0;
}

// Method C: Repeated division
function isPowerOfTwoC(int $x): bool {
    if ($x <= 0) return false;
    while ($x % 2 === 0) {
        $x /= 2;
    }
    return $x === 1;
}

// Method D: Using logarithms
function isPowerOfTwoD(int $x): bool {
    if ($x <= 0) return false;
    $logv = log($x, 2);
    return abs($logv - round($logv)) < 1e-10;
}

$test1 = 16; // true
$test2 = 18; // false

echo "A: " . (isPowerOfTwoA($test1) ? "true" : "false") . ", " . (isPowerOfTwoA($test2) ? "true" : "false") . PHP_EOL;
echo "B: " . (isPowerOfTwoB($test1) ? "true" : "false") . ", " . (isPowerOfTwoB($test2) ? "true" : "false") . PHP_EOL;
echo "C: " . (isPowerOfTwoC($test1) ? "true" : "false") . ", " . (isPowerOfTwoC($test2) ? "true" : "false") . PHP_EOL;
echo "D: " . (isPowerOfTwoD($test1) ? "true" : "false") . ", " . (isPowerOfTwoD($test2) ? "true" : "false") . PHP_EOL;


/*
OUTPUT:

A: true, false
B: true, false
C: true, false
D: true, false

*/

 



answered Apr 2 by avibootz

Related questions

...