fork download
  1. // Lusi Alifatul Laila
  2.  
  3. <?php
  4. function hitungNomorBit($angka, $nomorBit) {
  5. // Cek jika nomor bit negatif, return null
  6. if ($nomorBit < 0) {
  7. return null;
  8. }
  9.  
  10. $currentBit = 0; // Untuk melacak posisi bit saat ini
  11. $result = 0; // Untuk menyimpan hasil
  12.  
  13. // Konversi angka ke biner dengan pembagian 2 berulang
  14. while ($angka > 0) {
  15. $bit = $angka % 2; // Ambil bit paling kanan
  16.  
  17. // Jika currentBit sama dengan nomorBit yang diminta
  18. if ($currentBit == $nomorBit) {
  19. // Hitung nilai desimal dari bit ini
  20. // Menggunakan left shift untuk menghitung 2^nomorBit
  21. $value = $bit * (1 << $nomorBit);
  22. return $value === 0 ? 0 : $value;
  23. }
  24.  
  25. $angka = (int)($angka / 2); // Geser ke bit berikutnya
  26. $currentBit++; // Increment posisi bit
  27. }
  28.  
  29. // Jika sampai sini berarti nomorBit melebihi panjang biner angka
  30. return null;
  31. }
  32.  
  33. // Test case
  34. echo hitungNomorBit(13, 0) ?? 'null'; // Output: 1
  35. echo "\n";
  36. echo hitungNomorBit(13, 1) ?? 'null'; // Output: 0
  37. echo "\n";
  38. echo hitungNomorBit(13, 2) ?? 'null'; // Output: 4
  39. echo "\n";
  40. echo hitungNomorBit(13, 3) ?? 'null'; // Output: 8
  41. echo "\n";
  42. echo hitungNomorBit(13, 4) ?? 'null'; // Output: null
  43. ?>
Success #stdin #stdout 0.03s 25960KB
stdin
Standard input is empty
stdout
// Lusi Alifatul Laila

1
0
4
8
null