fork download
  1.  
  2. <?php
  3. function hitungNomorBit($angka, $nomorBit) {
  4. // Konversi ke biner
  5. $biner = decbin($angka);
  6.  
  7. if ($nomorBit === 0) {
  8. // Cari posisi bit 1 paling kiri (paling signifikan)
  9. return strlen($biner) - strlen(ltrim($biner, '0'));
  10. } elseif ($nomorBit === 1) {
  11. // Hitung jumlah bit 1
  12. return substr_count($biner, '1');
  13. } elseif ($nomorBit === 2) {
  14. return null;
  15. }
  16.  
  17. return null;
  18. }
  19.  
  20. // Contoh penggunaan
  21. echo "Untuk angka 13:\n";
  22. echo "Representasi Biner: " . decbin(13) . "\n";
  23. echo "hitungNomorBit(13, 0): " . hitungNomorBit(13, 0) . "\n";
  24. echo "hitungNomorBit(13, 1): " . hitungNomorBit(13, 1) . "\n";
  25. echo "hitungNomorBit(13, 2): " . (hitungNomorBit(13, 2) ?? 'null') . "\n";
  26. ?>
  27.  
Success #stdin #stdout 0.02s 25804KB
stdin
Standard input is empty
stdout
Untuk angka 13:
Representasi Biner: 1101
hitungNomorBit(13, 0): 0
hitungNomorBit(13, 1): 3
hitungNomorBit(13, 2): null