fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Author: Nayaka Ghana Subrata
  5.  
  6. // 13
  7. // 1 1 0 1
  8. // (13, 1)
  9. // -> 1 (tag) 1 (tag) 0 (skip) 1 (tag) = 3
  10.  
  11. int hitungNomorBit(int angka, int nomorBit){
  12. if (nomorBit != 0 && nomorBit != 1) return -1;
  13. int res = 0;
  14.  
  15. while (angka > 0){
  16. // here, we can extract then shift to iterate the bits, so like take one and shift
  17. if ((angka & 1) == nomorBit) res++;
  18. angka >>= 1;
  19. }
  20. return res;
  21. }
  22.  
  23.  
  24. int main() {
  25. int angka, nomorBit;
  26. cin >> angka >> nomorBit;
  27.  
  28. int res = hitungNomorBit(angka, nomorBit);
  29.  
  30. // here, if the counted bit sum is none then it will return -1 that represents the null
  31. cout << res << endl;
  32. return 0;
  33. }
Success #stdin #stdout 0s 5284KB
stdin
1 0
stdout
0