fork download
  1. #include <stdio.h>
  2.  
  3. int hitungNomorBit(int angka, int nomorBit) {
  4. int positions[128];
  5.  
  6. int n = angka;
  7. int pos = 0;
  8. int count = 0;
  9.  
  10. // check the lowest bit each step; divide by 2 until 0
  11. while (n > 0) {
  12. if (n % 2 == 1) {
  13. positions[count] = pos; // remember where a 1-bit is
  14. count++;
  15. }
  16. n = n / 2;
  17. pos++;
  18. }
  19.  
  20. // return the spot that is asked for, check if it's valid
  21. if (nomorBit >= 0 && nomorBit < count - 1) {
  22. return positions[nomorBit] + 1; // start at 1
  23. }
  24. return -1; // null
  25. }
  26.  
  27. int main() {
  28. // the three examples from the question
  29. int tests[3][2] = {{13, 0}, {13, 1}, {13, 2}};
  30. for (int i = 0; i < 3; i++) {
  31. int r = hitungNomorBit(tests[i][0], tests[i][1]);
  32. if (r == -1) {
  33. printf("hitungNomorBit(%d, %d) -> mengeluarkan hasil null\n", tests[i][0], tests[i][1]);
  34. } else {
  35. printf("hitungNomorBit(%d, %d) -> mengeluarkan hasil bilangan desimal %d\n", tests[i][0], tests[i][1], r);
  36. }
  37. }
  38. return 0;
  39. }
Success #stdin #stdout 0s 5316KB
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