fork download
  1. function hitungNomorBit(angka, nomorBit) {
  2. if (nomorBit !== 0 && nomorBit !== 1) {
  3. return null;
  4. }
  5.  
  6. if (angka === 0) {
  7. if (nomorBit === 0) return 1;
  8. else return 0;
  9. }
  10.  
  11. let jumlahKemunculan = 0;
  12. let sisaBagi;
  13.  
  14. while (angka > 0) {
  15. sisaBagi = angka % 2;
  16.  
  17. if (sisaBagi === nomorBit) {
  18. jumlahKemunculan++;
  19. }
  20.  
  21. angka = (angka - sisaBagi) / 2;
  22. }
  23.  
  24. return jumlahKemunculan;
  25. }
  26.  
  27. // pengujian
  28. console.log(hitungNomorBit(13, 0));
  29. console.log(hitungNomorBit(13, 1));
  30. console.log(hitungNomorBit(13, 2));
  31.  
  32.  
Success #stdin #stdout 0.03s 16728KB
stdin
Standard input is empty
stdout
1
3
null