fork download
  1. #include <stdio.h>
  2.  
  3. int hitungNomorBit(int angka, int nomorBit) {
  4. if (nomorBit != 0 && nomorBit != 1) {
  5. return -1;
  6. }
  7. if (angka == 0) {
  8. if (nomorBit == 0) {
  9. return 1;
  10. } else {
  11. return 0;
  12. }
  13. }
  14.  
  15. int HasilAkhir = 0;
  16.  
  17. while (angka > 0) {
  18. int bitTerakhir = angka & 1;
  19.  
  20. if (bitTerakhir == nomorBit) {
  21. HasilAkhir++;
  22. }
  23.  
  24. angka = angka >> 1;
  25. }
  26.  
  27. return HasilAkhir;
  28. }
  29.  
  30. int main() {
  31. int angka_test = 13;
  32.  
  33. int hasil1 = hitungNomorBit(angka_test, 0);
  34. printf("hitungNomorBit(13, 0) => mengeluarkan hasil bilangan desimal %d\n", hasil1);
  35.  
  36. int hasil2 = hitungNomorBit(angka_test, 1);
  37. printf("hitungNomorBit(13, 1) => mengeluarkan hasil bilangan desimal %d\n", hasil2);
  38.  
  39. int hasil3 = hitungNomorBit(angka_test, 2);
  40.  
  41. if (hasil3 == -1) {
  42. printf("hitungNomorBit(13, 2) => mengeluarkan hasil null \n");
  43. } else {
  44. printf("hitungNomorBit(13, 2), %d\n", hasil3);
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0) => mengeluarkan hasil bilangan desimal 1
hitungNomorBit(13, 1) => mengeluarkan hasil bilangan desimal 3
hitungNomorBit(13, 2) => mengeluarkan hasil null