fork download
  1. <?php
  2.  
  3. function hitungNomorBit($angka, $nomorBit) {
  4. // Validasi input harus 0 atau 1
  5. if ($nomorBit !== 0 && $nomorBit !== 1) {
  6. return null;
  7. }
  8.  
  9. // Konversi manual dari desimal ke biner
  10. $biner = [];
  11. while ($angka > 0) {
  12. $sisa = $angka % 2;
  13. array_unshift($biner, $sisa); // tambahkan di depan array
  14. $angka = intdiv($angka, 2);
  15. }
  16.  
  17. // Hitung jumlah kemunculan nomorBit
  18. $jumlah = 0;
  19. foreach ($biner as $bit) {
  20. if ($bit === $nomorBit) {
  21. $jumlah++;
  22. }
  23. }
  24.  
  25. // Jika tidak ditemukan, kembalikan null
  26. return $jumlah > 0 ? $jumlah : null;
  27. }
  28.  
  29. // Contoh penggunaan
  30. echo "hitungNomorBit(13, 0) = " . var_export(hitungNomorBit(13, 0), true) . PHP_EOL;
  31. echo "hitungNomorBit(13, 1) = " . var_export(hitungNomorBit(13, 1), true) . PHP_EOL;
  32. echo "hitungNomorBit(13, 2) = " . var_export(hitungNomorBit(13, 2), true) . PHP_EOL;
  33.  
  34. ?>
  35.  
Success #stdin #stdout 0.03s 26212KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0) = 1
hitungNomorBit(13, 1) = 3
hitungNomorBit(13, 2) = NULL