fork download
  1.  
  2. <?php
  3. function hitungNomorBit($angka, $nomorBit) {
  4. // Konversi angka desimal ke representasi biner
  5. $biner = decbin($angka);
  6.  
  7. // Panjang total representasi biner
  8. $panjang_biner = strlen($biner);
  9.  
  10. // Periksa berbagai kondisi untuk nomorBit
  11. if ($nomorBit === 0) {
  12. // Hitung jumlah bit 1 dari kiri
  13. return substr_count($biner, '1');
  14. } elseif ($nomorBit === 1) {
  15. // Hitung jumlah bit 1 dari kanan
  16. $biner_dibalik = strrev($biner);
  17. return substr_count($biner_dibalik, '1');
  18. } elseif ($nomorBit === 2) {
  19. // Kembalikan null
  20. return null;
  21. } else {
  22. // Untuk nomorBit di luar 0, 1, 2
  23. return null;
  24. }
  25. }
  26.  
  27. // Contoh penggunaan
  28. echo "Contoh untuk angka 13:\n";
  29. echo "hitungNomorBit(13, 0): " . (hitungNomorBit(13, 0) ?? 'null') . "\n";
  30. echo "hitungNomorBit(13, 1): " . (hitungNomorBit(13, 1) ?? 'null') . "\n";
  31. echo "hitungNomorBit(13, 2): " . (hitungNomorBit(13, 2) ?? 'null') . "\n";
  32. ?>
  33.  
Success #stdin #stdout 0.03s 25980KB
stdin
Standard input is empty
stdout
Contoh untuk angka 13:
hitungNomorBit(13, 0): 3
hitungNomorBit(13, 1): 3
hitungNomorBit(13, 2): null