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