fork download
  1. <?php
  2. function hitungNomorBit(int $angka, int $nomorBit): ?int
  3. {
  4.  
  5. if ($nomorBit !== 0 && $nomorBit !== 1) {
  6.  
  7. return null;
  8. }
  9. if ($angka < 0) {
  10. return 0;
  11. }
  12.  
  13.  
  14. if ($angka === 0) {
  15. return ($nomorBit === 0) ? 1 : 0;
  16. }
  17.  
  18. $hitungan = 0;
  19. $tempAngka = $angka;
  20. while ($tempAngka > 0) {
  21. $bit = $tempAngka % 2;
  22.  
  23. if ($bit === $nomorBit) {
  24. $hitungan++;
  25. }
  26. $tempAngka = intdiv($tempAngka, 2);
  27. }
  28.  
  29. return $hitungan;
  30. }
  31.  
  32. echo "(13, 0) " . (hitungNomorBit(13, 0) ?? "null"). "<br>";
  33. echo "(13, 1) " . (hitungNomorBit(13, 1) ?? "null"). "<br>";
  34. echo "(13, 2) " . (hitungNomorBit(13, 2) ?? "null"). "<br>";
  35. echo "(0, 0) " . (hitungNomorBit(0, 0) ?? "null"). "<br>";
  36. echo "(0, 1) " . (hitungNomorBit(0, 1) ?? "null"). "<br>";
Success #stdin #stdout 0.04s 25416KB
stdin
Standard input is empty
stdout
(13, 0) 1<br>(13, 1) 3<br>(13, 2) null<br>(0, 0) 1<br>(0, 1) 0<br>