fork download
  1. function desimalKeBiner(angka) {
  2. if (angka === 0) return "0";
  3.  
  4. let biner = "";
  5. while (angka > 0) {
  6. biner = (angka % 2 === 0 ? "0" : "1") + biner;
  7. angka = Math.floor(angka / 2);
  8. }
  9. return biner;
  10. }
  11.  
  12. function hitungNomorBit(angka, nomorBit) {
  13. if (nomorBit !== 0 && nomorBit !== 1) {
  14. return null;
  15. }
  16.  
  17. const biner = desimalKeBiner(angka);
  18. let jumlah = 0;
  19. for (let i = 0; i < biner.length; i++) {
  20. if (parseInt(biner[i]) === nomorBit) {
  21. jumlah++;
  22. }
  23. }
  24. return jumlah;
  25. }
  26.  
  27. function cetakHasil(angka, nomorBit) {
  28. const hasil = hitungNomorBit(angka, nomorBit);
  29. console.log(`hitungNomorBit(${angka}, ${nomorBit}) -> ${hasil !== null ? hasil : "null"}`);
  30. }
  31.  
  32. console.log("Binary of 13:", desimalKeBiner(13));
  33. cetakHasil(13, 0);
  34. cetakHasil(13, 1);
  35. cetakHasil(13, 2);
  36.  
  37. console.log("\nBinary of 7:", desimalKeBiner(7));
  38. cetakHasil(7, 0);
  39. cetakHasil(7, 1);
  40.  
  41. console.log("\nBinary of 0:", desimalKeBiner(0));
  42. cetakHasil(0, 0);
  43. cetakHasil(0, 1);
  44.  
  45. console.log("\nBinary of 8:", desimalKeBiner(8));
  46. cetakHasil(8,0);
  47. cetakHasil(8,1);
Success #stdin #stdout 0.05s 16500KB
stdin
Standard input is empty
stdout
Binary of 13: 1101
hitungNomorBit(13, 0) -> 1
hitungNomorBit(13, 1) -> 3
hitungNomorBit(13, 2) -> null

Binary of 7: 111
hitungNomorBit(7, 0) -> 0
hitungNomorBit(7, 1) -> 3

Binary of 0: 0
hitungNomorBit(0, 0) -> 1
hitungNomorBit(0, 1) -> 0

Binary of 8: 1000
hitungNomorBit(8, 0) -> 3
hitungNomorBit(8, 1) -> 1