function hitungNomorBit($angka, $nomorBit) {
// Konversi angka desimal ke representasi biner
// Panjang total representasi biner
$panjang_biner = strlen($biner);
// Periksa berbagai kondisi untuk nomorBit
if ($nomorBit === 0) {
// Hitung jumlah bit 1 dari kiri
} elseif ($nomorBit === 1) {
// Hitung jumlah bit 1 dari kanan
$biner_dibalik = strrev($biner); } elseif ($nomorBit === 2) {
// Kembalikan null
return null;
} else {
// Untuk nomorBit di luar 0, 1, 2
return null;
}
}
// Contoh penggunaan
echo "Contoh untuk angka 13:\n";
echo "hitungNomorBit(13, 0): " . (hitungNomorBit(13, 0) ?? 'null') . "\n";
echo "hitungNomorBit(13, 1): " . (hitungNomorBit(13, 1) ?? 'null') . "\n";
echo "hitungNomorBit(13, 2): " . (hitungNomorBit(13, 2) ?? 'null') . "\n";
CgpmdW5jdGlvbiBoaXR1bmdOb21vckJpdCgkYW5na2EsICRub21vckJpdCkgewogICAgLy8gS29udmVyc2kgYW5na2EgZGVzaW1hbCBrZSByZXByZXNlbnRhc2kgYmluZXIKICAgICRiaW5lciA9IGRlY2JpbigkYW5na2EpOwogICAgCiAgICAvLyBQYW5qYW5nIHRvdGFsIHJlcHJlc2VudGFzaSBiaW5lcgogICAgJHBhbmphbmdfYmluZXIgPSBzdHJsZW4oJGJpbmVyKTsKICAgIAogICAgLy8gUGVyaWtzYSBiZXJiYWdhaSBrb25kaXNpIHVudHVrIG5vbW9yQml0CiAgICBpZiAoJG5vbW9yQml0ID09PSAwKSB7CiAgICAgICAgLy8gSGl0dW5nIGp1bWxhaCBiaXQgMSBkYXJpIGtpcmkKICAgICAgICByZXR1cm4gc3Vic3RyX2NvdW50KCRiaW5lciwgJzEnKTsKICAgIH0gZWxzZWlmICgkbm9tb3JCaXQgPT09IDEpIHsKICAgICAgICAvLyBIaXR1bmcganVtbGFoIGJpdCAxIGRhcmkga2FuYW4KICAgICAgICAkYmluZXJfZGliYWxpayA9IHN0cnJldigkYmluZXIpOwogICAgICAgIHJldHVybiBzdWJzdHJfY291bnQoJGJpbmVyX2RpYmFsaWssICcxJyk7CiAgICB9IGVsc2VpZiAoJG5vbW9yQml0ID09PSAyKSB7CiAgICAgICAgLy8gS2VtYmFsaWthbiBudWxsCiAgICAgICAgcmV0dXJuIG51bGw7CiAgICB9IGVsc2UgewogICAgICAgIC8vIFVudHVrIG5vbW9yQml0IGRpIGx1YXIgMCwgMSwgMgogICAgICAgIHJldHVybiBudWxsOwogICAgfQp9CgovLyBDb250b2ggcGVuZ2d1bmFhbgplY2hvICJDb250b2ggdW50dWsgYW5na2EgMTM6XG4iOwplY2hvICJoaXR1bmdOb21vckJpdCgxMywgMCk6ICIgLiAoaGl0dW5nTm9tb3JCaXQoMTMsIDApID8/ICdudWxsJykgLiAiXG4iOwplY2hvICJoaXR1bmdOb21vckJpdCgxMywgMSk6ICIgLiAoaGl0dW5nTm9tb3JCaXQoMTMsIDEpID8/ICdudWxsJykgLiAiXG4iOwplY2hvICJoaXR1bmdOb21vckJpdCgxMywgMik6ICIgLiAoaGl0dW5nTm9tb3JCaXQoMTMsIDIpID8/ICdudWxsJykgLiAiXG4iOwoK
function hitungNomorBit($angka, $nomorBit) {
// Konversi angka desimal ke representasi biner
$biner = decbin($angka);
// Panjang total representasi biner
$panjang_biner = strlen($biner);
// Periksa berbagai kondisi untuk nomorBit
if ($nomorBit === 0) {
// Hitung jumlah bit 1 dari kiri
return substr_count($biner, '1');
} elseif ($nomorBit === 1) {
// Hitung jumlah bit 1 dari kanan
$biner_dibalik = strrev($biner);
return substr_count($biner_dibalik, '1');
} elseif ($nomorBit === 2) {
// Kembalikan null
return null;
} else {
// Untuk nomorBit di luar 0, 1, 2
return null;
}
}
// Contoh penggunaan
echo "Contoh untuk angka 13:\n";
echo "hitungNomorBit(13, 0): " . (hitungNomorBit(13, 0) ?? 'null') . "\n";
echo "hitungNomorBit(13, 1): " . (hitungNomorBit(13, 1) ?? 'null') . "\n";
echo "hitungNomorBit(13, 2): " . (hitungNomorBit(13, 2) ?? 'null') . "\n";