fork download
  1. // your code goes here
  2. function hitungNomorBit(angka, nomorBit) {
  3. // Konversi desimal ke biner secara manual (array dari kiri ke kanan)
  4. let biner = [];
  5. let n = angka;
  6.  
  7. if (n === 0) {
  8. biner.push(0);
  9. }
  10.  
  11. while (n > 0) {
  12. biner.unshift(n % 2); // Tambahkan ke awal agar urut dari MSB
  13. n = Math.floor(n / 2);
  14. }
  15.  
  16. // Cek jika panjang bit kurang dari nomorBit + 1
  17. if (biner.length < nomorBit + 1) {
  18. return null;
  19. }
  20.  
  21. // Ambil (nomorBit + 1) bit dari kiri
  22. let bagian = biner.slice(0, nomorBit + 1);
  23.  
  24. // Hitung jumlah bit yang bernilai 1
  25. let jumlah = 0;
  26. for (let i = 0; i < bagian.length; i++) {
  27. if (bagian[i] === 1) {
  28. jumlah += 1;
  29. }
  30. }
  31.  
  32. return jumlah;
  33. }
  34.  
  35. // output sesuai contoh soal yang diberikan
  36. console.log(hitungNomorBit(13, 0)); // 1
  37. console.log(hitungNomorBit(13, 1)); // 3
  38. console.log(hitungNomorBit(13, 2)); // null
  39.  
Success #stdin #stdout 0.04s 19148KB
stdin
Standard input is empty
stdout
1
2
2