fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int hitungNomorBit(int angka, int nomorBit);
  5. string intToBin(int angka);
  6.  
  7.  
  8. int main() {
  9. cout << "hitungNomorBit(13, 0): " << hitungNomorBit(13, 0) << endl;
  10. cout << "hitungNomorBit(13, 1): " << hitungNomorBit(13, 1) << endl;
  11. cout << "hitungNomorBit(13, 2): " << hitungNomorBit(13, 2) << endl;
  12. cout << "hitungNomorBit(128, 0): " << hitungNomorBit(128, 0) << endl;
  13. cout << "hitungNomorBit(128, 1): " << hitungNomorBit(128, 1) << endl;
  14. return 0;
  15. }
  16.  
  17. int hitungNomorBit(int angka, int nomorBit)
  18. {
  19. string bin {intToBin(angka)};
  20. int count {0};
  21.  
  22. if (nomorBit == 0 || nomorBit == 1)
  23. {
  24. for (char c: bin)
  25. {
  26. if (c - '0' == nomorBit)
  27. {
  28. count++;
  29. }
  30. }
  31. return count;
  32. }
  33. else
  34. {
  35. return -1; // -1 dipakai sebagai substitut dari null
  36. }
  37. }
  38.  
  39. string intToBin(int angka)
  40. {
  41. string out {};
  42. int sisa {0};
  43.  
  44. while (angka != 0)
  45. {
  46. sisa = angka % 2;
  47. angka /= 2;
  48. out.append(1, sisa + '0');
  49. }
  50.  
  51. return out;
  52. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0): 1
hitungNomorBit(13, 1): 3
hitungNomorBit(13, 2): -1
hitungNomorBit(128, 0): 7
hitungNomorBit(128, 1): 1