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