fork download
  1. <?php
  2.  
  3. function hitungNomorBit(int $angka, int $nomorBit): ?int {
  4. if ($angka < 0 || $nomorBit < 0) return null;
  5.  
  6. $biner = [];
  7. while ($angka > 0) {
  8. array_unshift($biner, $angka % 2);
  9. $angka = intdiv($angka, 2);
  10. }
  11.  
  12. if ($nomorBit >= count($biner)) {
  13. return null;
  14. }
  15.  
  16. $jumlah = 0;
  17. for ($i = $nomorBit; $i < count($biner); $i++) {
  18. if ($biner[$i] === 1) {
  19. $jumlah++;
  20. }
  21. }
  22.  
  23. return $jumlah;
  24. }
  25.  
  26. echo "hitungNomorBit(13, 0) = " . hitungNomorBit(13, 0) . "\n"; // 1 (bit: 1)
  27. echo "hitungNomorBit(13, 1) = " . hitungNomorBit(13, 1) . "\n"; // 3 (bit: 1, 0, 1)
  28. echo "hitungNomorBit(13, 2) = ";
  29. var_dump(hitungNomorBit(13, 2));
  30.  
  31.  
Success #stdin #stdout 0.04s 26340KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0) = 3
hitungNomorBit(13, 1) = 2
hitungNomorBit(13, 2) = int(1)