fork download
  1. // your code goes here
  2. function hitungNomorBit(angka, nomorBit) {
  3. //validasi
  4. if (nomorBit !== 0 && nomorBit !== 1) {
  5. return null;
  6. }
  7.  
  8. // konversi biner
  9. var biner = [];
  10. var n = angka;
  11.  
  12. if(n === 0) {
  13. biner.push(0);
  14. } else {
  15. while (n > 0) {
  16. var sisa = n % 2;
  17. biner.unshift(sisa);
  18. n = Math.floor(n/2);
  19. }
  20. }
  21.  
  22. //hitung jumlah bit
  23. var jumlah = 0;
  24. for (var i = 0; i < biner.length; i++) {
  25. if (biner[i] === nomorBit){
  26. jumlah++;
  27. }
  28. }
  29.  
  30. return jumlah;
  31. }
  32.  
  33. print(hitungNomorBit(13, 0));
  34. print(hitungNomorBit(13, 1));
  35. print(hitungNomorBit(13, 2));
Success #stdin #stdout 0.03s 16880KB
stdin
Standard input is empty
stdout
1
3
null