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