function hitungNomorBit(int $angka, int $nomorBit): ?int {
if ($angka < 0 || $nomorBit < 0) return null;
// Konversi manual desimal ke biner dari MSB ke LSB
$biner = [];
while ($angka > 0) {
$angka = intdiv($angka, 2);
}
if ($nomorBit >= count($biner)) return null;
$jumlah = 0;
for ($i = 0; $i <= $nomorBit; $i++) {
if ($biner[$i] === 1) {
$jumlah++;
}
}
return $jumlah;
}
echo hitungNomorBit(13, 0) . "\n";
echo hitungNomorBit(13, 1) . "\n";
ZnVuY3Rpb24gaGl0dW5nTm9tb3JCaXQoaW50ICRhbmdrYSwgaW50ICRub21vckJpdCk6ID9pbnQgewogICAgaWYgKCRhbmdrYSA8IDAgfHwgJG5vbW9yQml0IDwgMCkgcmV0dXJuIG51bGw7CiAKICAgIC8vIEtvbnZlcnNpIG1hbnVhbCBkZXNpbWFsIGtlIGJpbmVyIGRhcmkgTVNCIGtlIExTQgogICAgJGJpbmVyID0gW107CiAgICB3aGlsZSAoJGFuZ2thID4gMCkgewogICAgICAgIGFycmF5X3Vuc2hpZnQoJGJpbmVyLCAkYW5na2EgJSAyKTsKICAgICAgICAkYW5na2EgPSBpbnRkaXYoJGFuZ2thLCAyKTsKICAgIH0KIAogICAgaWYgKCRub21vckJpdCA+PSBjb3VudCgkYmluZXIpKSByZXR1cm4gbnVsbDsKIAogICAgJGp1bWxhaCA9IDA7CiAgICBmb3IgKCRpID0gMDsgJGkgPD0gJG5vbW9yQml0OyAkaSsrKSB7CiAgICAgICAgaWYgKCRiaW5lclskaV0gPT09IDEpIHsKICAgICAgICAgICAgJGp1bWxhaCsrOwogICAgICAgIH0KICAgIH0KIAogICAgcmV0dXJuICRqdW1sYWg7Cn0KCmVjaG8gaGl0dW5nTm9tb3JCaXQoMTMsIDApIC4gIlxuIjsgCmVjaG8gaGl0dW5nTm9tb3JCaXQoMTMsIDEpIC4gIlxuIjsgCnZhcl9kdW1wKGhpdHVuZ05vbW9yQml0KDEzLCAyKSk7
function hitungNomorBit(int $angka, int $nomorBit): ?int {
if ($angka < 0 || $nomorBit < 0) return null;
// Konversi manual desimal ke biner dari MSB ke LSB
$biner = [];
while ($angka > 0) {
array_unshift($biner, $angka % 2);
$angka = intdiv($angka, 2);
}
if ($nomorBit >= count($biner)) return null;
$jumlah = 0;
for ($i = 0; $i <= $nomorBit; $i++) {
if ($biner[$i] === 1) {
$jumlah++;
}
}
return $jumlah;
}
echo hitungNomorBit(13, 0) . "\n";
echo hitungNomorBit(13, 1) . "\n";
var_dump(hitungNomorBit(13, 2));