fork download
  1. <?php
  2. function hitungNomorBit(int $angka, int $nomorBit): ?int {
  3. if ($angka < 0 || $nomorBit < 0) return null;
  4.  
  5. // Konversi manual desimal ke biner dari MSB ke LSB
  6. $biner = [];
  7. while ($angka > 0) {
  8. array_unshift($biner, $angka % 2);
  9. $angka = intdiv($angka, 2);
  10. }
  11.  
  12. if ($nomorBit >= count($biner)) return null;
  13.  
  14. $jumlah = 0;
  15. for ($i = 0; $i <= $nomorBit; $i++) {
  16. if ($biner[$i] === 1) {
  17. $jumlah++;
  18. }
  19. }
  20.  
  21. return $jumlah;
  22. }
  23.  
  24. echo hitungNomorBit(13, 0) . "\n"; // Output: 1 (bit 0 = 1)
  25. echo hitungNomorBit(13, 1) . "\n"; // Output: 3 (bit 1 ke bawah: 1+0+1)
  26. var_dump(hitungNomorBit(13, 2)); // Output: null (bit 2 = 0, hanya sampai 2, jadi total 2 bit yang 1)
Success #stdin #stdout 0.03s 26188KB
stdin
Standard input is empty
stdout
1
2
int(2)