fork download
  1. public class Main
  2. {
  3. public static void main(String[] args) {
  4. System.out.println(hitungNomorBit(13, 0));
  5. System.out.println(hitungNomorBit(13, 1));
  6. System.out.println(hitungNomorBit(13, 2));
  7. }
  8.  
  9. public static Integer hitungNomorBit(int angka, int nomorBit) {
  10. int zero_counter = 0;
  11. int one_counter = 0;
  12. int temp = 0;
  13.  
  14. while(angka > 0) {
  15. temp = angka % 2;
  16.  
  17. if(temp == 0) {
  18. zero_counter++;
  19. } else if (temp == 1) {
  20. one_counter++;
  21. }
  22.  
  23. angka = angka / 2;
  24. }
  25.  
  26. // Angka biner tidak perlu ditampilkan maka langsung ke penghitungan nomorBit.
  27.  
  28. if(nomorBit == 0) {
  29. return zero_counter;
  30. } else if(nomorBit == 1) {
  31. return one_counter;
  32. }
  33. return null;
  34. }
  35. }
  36.  
Success #stdin #stdout 0.11s 54700KB
stdin
Standard input is empty
stdout
1
3
null