fork download
  1. function hitungNomorBit(int $angka, int $nomorBit): ?int {
  2. if ($angka < 0 || $nomorBit < 0) return null;
  3.  
  4. // Konversi manual desimal ke biner dari MSB ke LSB
  5. $biner = [];
  6. while ($angka > 0) {
  7. array_unshift($biner, $angka % 2);
  8. $angka = intdiv($angka, 2);
  9. }
  10.  
  11. if ($nomorBit >= count($biner)) return null;
  12.  
  13. $jumlah = 0;
  14. for ($i = 0; $i <= $nomorBit; $i++) {
  15. if ($biner[$i] === 1) {
  16. $jumlah++;
  17. }
  18. }
  19.  
  20. return $jumlah;
  21. }
  22.  
Success #stdin #stdout 0.04s 25996KB
stdin
Standard input is empty
stdout
function hitungNomorBit(int $angka, int $nomorBit): ?int {
    if ($angka < 0 || $nomorBit < 0) return null;

    // Konversi manual desimal ke biner dari MSB ke LSB
    $biner = [];
    while ($angka > 0) {
        array_unshift($biner, $angka % 2);
        $angka = intdiv($angka, 2);
    }

    if ($nomorBit >= count($biner)) return null;

    $jumlah = 0;
    for ($i = 0; $i <= $nomorBit; $i++) {
        if ($biner[$i] === 1) {
            $jumlah++;
        }
    }

    return $jumlah;
}