fork download
  1. <?php
  2.  
  3. function hitungNomorBit($angka, $nomorBit) {
  4. if ($nomorBit !== 0 && $nomorBit !== 1) {
  5. return null;
  6. }
  7.  
  8. $biner = [];
  9. while ($angka > 0) {
  10. $sisa = $angka % 2;
  11. array_unshift($biner, $sisa);
  12. $angka = intdiv($angka, 2);
  13. }
  14.  
  15. $jumlah = 0;
  16. foreach ($biner as $bit) {
  17. if ($bit === $nomorBit) {
  18. $jumlah++;
  19. }
  20. }
  21.  
  22. return $jumlah > 0 ? $jumlah : null;
  23. }
  24.  
  25. echo "hitungNomorBit(13, 0) = " . var_export(hitungNomorBit(13, 0), true) . PHP_EOL;
  26. echo "hitungNomorBit(13, 1) = " . var_export(hitungNomorBit(13, 1), true) . PHP_EOL;
  27. echo "hitungNomorBit(13, 2) = " . var_export(hitungNomorBit(13, 2), true) . PHP_EOL;
  28.  
  29. ?>
  30.  
Success #stdin #stdout 0.02s 26228KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0) = 1
hitungNomorBit(13, 1) = 3
hitungNomorBit(13, 2) = NULL