fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int hitungNomorBit(int angka, int nomorBit) {
  5. // Validasi input nomorBit harus 0 atau 1
  6. if (nomorBit != 0 && nomorBit != 1) {
  7. return -1; // sebagai pengganti NULL
  8. }
  9.  
  10. // Konversi angka desimal ke biner manual
  11. int biner[32]; // cukup untuk 32 bit
  12. int i = 0;
  13. while (angka > 0) {
  14. biner[i] = angka % 2;
  15. angka /= 2;
  16. i++;
  17. }
  18.  
  19. // Hitung jumlah kemunculan nomorBit
  20. int jumlah = 0;
  21. for (int j = 0; j < i; j++) {
  22. if (biner[j] == nomorBit) {
  23. jumlah++;
  24. }
  25. }
  26.  
  27. // Jika tidak ditemukan, anggap null -> return -1
  28. if (jumlah == 0) {
  29. return -1;
  30. }
  31.  
  32. return jumlah;
  33. }
  34.  
  35. int main() {
  36. cout << "hitungNomorBit(13, 0) = " << hitungNomorBit(13, 0) << endl; // 1
  37. cout << "hitungNomorBit(13, 1) = " << hitungNomorBit(13, 1) << endl; // 3
  38. cout << "hitungNomorBit(13, 2) = " << hitungNomorBit(13, 2) << endl; // -1 (NULL)
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0.03s 26052KB
stdin
Standard input is empty
stdout
#include <iostream>
using namespace std;

int hitungNomorBit(int angka, int nomorBit) {
    // Validasi input nomorBit harus 0 atau 1
    if (nomorBit != 0 && nomorBit != 1) {
        return -1; // sebagai pengganti NULL
    }

    // Konversi angka desimal ke biner manual
    int biner[32]; // cukup untuk 32 bit
    int i = 0;
    while (angka > 0) {
        biner[i] = angka % 2;
        angka /= 2;
        i++;
    }

    // Hitung jumlah kemunculan nomorBit
    int jumlah = 0;
    for (int j = 0; j < i; j++) {
        if (biner[j] == nomorBit) {
            jumlah++;
        }
    }

    // Jika tidak ditemukan, anggap null -> return -1
    if (jumlah == 0) {
        return -1;
    }

    return jumlah;
}

int main() {
    cout << "hitungNomorBit(13, 0) = " << hitungNomorBit(13, 0) << endl; // 1
    cout << "hitungNomorBit(13, 1) = " << hitungNomorBit(13, 1) << endl; // 3
    cout << "hitungNomorBit(13, 2) = " << hitungNomorBit(13, 2) << endl; // -1 (NULL)
    return 0;
}