fork download
  1. function hitungNomorBit(angka, nomorBit) {
  2. // Konversi manual dari desimal ke biner
  3. let biner = "";
  4. let temp = angka;
  5.  
  6. if (temp === 0) {
  7. biner = "0";
  8. } else {
  9. while (temp > 0) {
  10. biner = (temp % 2) + biner;
  11. temp = Math.floor(temp / 2);
  12. }
  13. }
  14.  
  15. // Cari posisi bit yang bernilai 1
  16. let posisiBit = [];
  17. for (let i = biner.length - 1; i >= 0; i--) {
  18. if (biner[i] === '1') {
  19. posisiBit.push(biner.length - 1 - i);
  20. }
  21. }
  22.  
  23. if (nomorBit === 0 && posisiBit.length > 1) {
  24. return 1;
  25. } else if (nomorBit === 1 && posisiBit.length > 2) {
  26. return posisiBit[2];
  27. } else {
  28. return null;
  29. }
  30. }
  31.  
  32. console.log(hitungNomorBit(13, 0));
  33. console.log(hitungNomorBit(13, 1));
  34. console.log(hitungNomorBit(13, 2));
Success #stdin #stdout 0.05s 18940KB
stdin
Standard input is empty
stdout
1
3
null