fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. int hitungNomorBit(int angka, int nomorBit) {
  5. // Konversi desimal ke biner
  6. std::vector<int> biner;
  7.  
  8. // Jika angka negatif, perlakukan sebagai bilangan positif
  9. if (angka < 0) {
  10. angka = -angka;
  11. }
  12.  
  13. // Melakukan konversi angka desimal ke biner
  14. while (angka > 0) {
  15. biner.push_back(angka % 2); // simpan bit di posisi terakhir
  16. angka /= 2; // bagi dengan 2 untuk hilangkan bit yang telah dihitung
  17. }
  18.  
  19. // Menghitung nomor bit berdasarkan nomor yang diminta
  20. if (nomorBit < 0 || nomorBit >= biner.size()) {
  21. return 0; // Jika nomorBit diluar jangkauan, kembalikan 0
  22. }
  23.  
  24. int totalBit = 0;
  25.  
  26. // Hitung nomor bit yang diminta
  27. for (int i = nomorBit; i < biner.size(); ++i) {
  28. totalBit += biner[i];
  29. }
  30.  
  31. return totalBit;
  32. }
  33.  
  34. int main() {
  35. std::cout << "hitungNomorBit(13, 0) = " << hitungNomorBit(13, 0) << std::endl; // Output: 1
  36. std::cout << "hitungNomorBit(13, 1) = " << hitungNomorBit(13, 1) << std::endl; // Output: 3
  37. std::cout << "hitungNomorBit(13, 2) = " << hitungNomorBit(13, 2) << std::endl; // Output: 0
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0) = 3
hitungNomorBit(13, 1) = 2
hitungNomorBit(13, 2) = 2