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