fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. public class Main {
  6. static Integer hitungNomorBit(int angka, int nomorBit) {
  7. if (nomorBit != 0 && nomorBit != 1) {
  8. return null;
  9. }
  10.  
  11. String biner = "";
  12. int n = angka;
  13.  
  14. if (n == 0) {
  15. biner = "0";
  16. }
  17.  
  18. while (n > 0) {
  19. biner = (n % 2) + biner;
  20. n = n / 2;
  21. }
  22.  
  23. int jumlah = 0;
  24. for (int i = 0; i < biner.length(); i++) {
  25. if (biner.charAt(i) - '0' == nomorBit) {
  26. jumlah++;
  27. }
  28. }
  29.  
  30. return jumlah;
  31. }
  32.  
  33. public static void main (String[] args) throws java.lang.Exception
  34. {
  35. System.out.println(hitungNomorBit(13, 0));
  36. System.out.println(hitungNomorBit(13, 1));
  37. System.out.println(hitungNomorBit(13, 2));
  38. }
  39. }
Success #stdin #stdout 0.1s 55448KB
stdin
Standard input is empty
stdout
1
3
null