fork download
  1. function hitungNomorBit(angka, nomorBit) {
  2. if (nomorBit !== 0 && nomorBit !== 1) {
  3. return null;
  4. }
  5.  
  6. if (angka === 0) {
  7. return (nomorBit === 0) ? 1 : 0;
  8. }
  9.  
  10.  
  11. let angkaBiner = [];
  12. let a = angka;
  13.  
  14. while (a > 0) {
  15. angkaBiner.push(a % 2);
  16. a = Math.floor(a / 2);
  17. }
  18.  
  19. let jumlah = 0;
  20. for (let i = 0; i < angkaBiner.length; i++) {
  21. if (angkaBiner[i] === nomorBit) {
  22. jumlah++;
  23. }
  24. }
  25.  
  26. return jumlah;
  27. }
  28.  
  29. console.log(hitungNomorBit(13, 1));
Success #stdin #stdout 0.04s 16772KB
stdin
1
2
10
42
11
stdout
3