fork download
  1. <?php
  2.  
  3. function hitungNomorBit(int $angka, int $nomorBit): ?int
  4. {
  5. if ($nomorBit !== 0 && $nomorBit !== 1) {
  6. return null;
  7. }
  8.  
  9. $jumlah = 0;
  10.  
  11. while ($angka > 0) {
  12. $bit = $angka % 2;
  13. if ($bit === $nomorBit) {
  14. $jumlah++;
  15. }
  16. $angka = intdiv($angka, 2);
  17. }
  18.  
  19. return $jumlah;
  20. }
  21.  
  22.  
  23.  
  24. // Representasi bilangan biner dari angka 13 adalah 1101
  25. echo hitungNomorBit(57, 0) . PHP_EOL;
  26. echo hitungNomorBit(57, 1) . PHP_EOL;
  27. echo var_export(hitungNomorBit(57, 2), true);
  28.  
Success #stdin #stdout 0.03s 25832KB
stdin
Standard input is empty
stdout
2
4
NULL