<?php
function hitungNomorBit($angka, $nomorBit) {
// Validasi input
if ($angka < 0 || $nomorBit < 0) {
return null; // Tidak valid jika angka atau nomorBit negatif
}
// Konversi angka desimal ke biner secara manual
$biner = "";
$n = $angka;
while ($n > 0) {
$biner = ($n % 2) . $biner; // Ambil sisa pembagian 2 sebagai bit (0 atau 1)
$n = (int)($n / 2); // Bagi angka dengan 2 dan ambil bagian integer
}
// Jika biner kosong, berarti angka adalah 0
if ($biner === "") {
$biner = "0";
}
// Hitung jumlah bit berdasarkan nomorBit yang diminta
$bitCount = 0;
for ($i = 0; $i < strlen($biner); $i++) { if ((int)$biner[$i] === $nomorBit) {
$bitCount++;
}
}
// Jika nomorBit bukan 0 atau 1, return null
if ($nomorBit !== 0 && $nomorBit !== 1) {
return null;
}
return $bitCount;
}
// Contoh penggunaan
echo hitungNomorBit(13, 0) . "\n"; // Output: 1
echo hitungNomorBit(13, 1) . "\n"; // Output: 3
echo hitungNomorBit(13, 2) . "\n"; // Output: null
?>
PD9waHAKZnVuY3Rpb24gaGl0dW5nTm9tb3JCaXQoJGFuZ2thLCAkbm9tb3JCaXQpIHsKICAgIC8vIFZhbGlkYXNpIGlucHV0CiAgICBpZiAoJGFuZ2thIDwgMCB8fCAkbm9tb3JCaXQgPCAwKSB7CiAgICAgICAgcmV0dXJuIG51bGw7IC8vIFRpZGFrIHZhbGlkIGppa2EgYW5na2EgYXRhdSBub21vckJpdCBuZWdhdGlmCiAgICB9CgogICAgLy8gS29udmVyc2kgYW5na2EgZGVzaW1hbCBrZSBiaW5lciBzZWNhcmEgbWFudWFsCiAgICAkYmluZXIgPSAiIjsKICAgICRuID0gJGFuZ2thOwogICAgd2hpbGUgKCRuID4gMCkgewogICAgICAgICRiaW5lciA9ICgkbiAlIDIpIC4gJGJpbmVyOyAvLyBBbWJpbCBzaXNhIHBlbWJhZ2lhbiAyIHNlYmFnYWkgYml0ICgwIGF0YXUgMSkKICAgICAgICAkbiA9IChpbnQpKCRuIC8gMik7IC8vIEJ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