fork download
  1. <?php
  2.  
  3. function hitungNomorBit(int $angka, int $nomorBit): ?int {
  4. if ($angka < 0 || $nomorBit < 0) return null;
  5.  
  6. // Konversi manual desimal ke biner (dari MSB ke LSB)
  7. $biner = [];
  8. while ($angka > 0) {
  9. array_unshift($biner, $angka % 2);
  10. $angka = intdiv($angka, 2);
  11. }
  12.  
  13. // Jika nomorBit tidak ada, return null
  14. if ($nomorBit >= count($biner)) {
  15. return null;
  16. }
  17.  
  18. // Hitung jumlah bit 1 dari posisi nomorBit sampai akhir (ke kanan)
  19. $jumlah = 0;
  20. for ($i = $nomorBit; $i < count($biner); $i++) {
  21. if ($biner[$i] === 1) {
  22. $jumlah++;
  23. }
  24. }
  25.  
  26. return $jumlah;
  27. }
  28.  
  29. // Fungsi cetak hasil dengan format sesuai soal
  30. function tampilkanHasil($angka, $nomorBit) {
  31. $hasil = hitungNomorBit($angka, $nomorBit);
  32. if (is_null($hasil)) {
  33. echo "hitungNomorBit($angka, $nomorBit) = NULL\n";
  34. } else {
  35. echo "hitungNomorBit($angka, $nomorBit) = $hasil\n";
  36. }
  37. }
  38.  
  39. // Tes sesuai soal
  40. tampilkanHasil(13, 0); // → 1
  41. tampilkanHasil(13, 1); // → 3
  42. tampilkanHasil(13, 2); // → NULL
  43.  
Success #stdin #stdout 0.03s 26056KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0) = 3
hitungNomorBit(13, 1) = 2
hitungNomorBit(13, 2) = 1