fork download
  1.  
  2. public class Main {
  3. public static int hitungNomorBit (int angka, int nomorBit)
  4. {
  5. int temp = angka;
  6. int panjang = 0;
  7.  
  8. if (temp ==0) {
  9. panjang = 1;
  10. }else {
  11. while (temp > 0 ) {
  12. temp = temp / 2;
  13. panjang++;
  14. }
  15. }
  16. if (nomorBit < 0 || nomorBit >= panjang) {
  17. return -1;
  18. }
  19. int[] bit = new int[panjang];
  20. temp = angka;
  21. for ( int i = panjang -1; i >=0; i--){
  22. bit[i] = temp % 2;
  23. temp = temp / 2;
  24. }
  25. if (bit[nomorBit] == 0 ) {
  26. return -1;
  27. }
  28. int hasil = 0;
  29. for (int i = 0; i<= nomorBit; i++ ) {
  30. hasil = hasil * 2 + bit[i];
  31. }
  32. return hasil;
  33. }
  34. public static void main(String[] args) {
  35. int hasil1=hitungNomorBit (13, 0);
  36. int hasil2=hitungNomorBit (13, 1);
  37. int hasil3=hitungNomorBit (13, 2);
  38. System.out.println(hasil1 == -1 ? "null" : hasil1);
  39. System.out.println(hasil2 == -1 ? "null" : hasil2);
  40. System.out.println(hasil3 == -1 ? "null" : hasil3);
  41. ;
  42. }
  43. }
Success #stdin #stdout 0.07s 54496KB
stdin
Standard input is empty
stdout
1
3
null