fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3.  
  4. /* Name of the class has to be "Main" only if the class is public. */
  5. class Ideone
  6. {
  7. public static void main (String[] args) throws java.lang.Exception
  8. {
  9. System.out.println(hitungNomorBit(13, 0)); // 1
  10. System.out.println(hitungNomorBit(13, 1)); // 3
  11. System.out.println(hitungNomorBit(13, 2)); // 0 (pengganti null)
  12. System.out.println(hitungNomorBit(Integer.MAX_VALUE, 1)); // 31 bit 1
  13. System.out.println(hitungNomorBit(Integer.MIN_VALUE, 1)); // 1 bit 1 dari sign bit
  14. System.out.println(hitungNomorBit(0, 0)); // 1 bit 0
  15. System.out.println(hitungNomorBit(-1, 1)); // 32 bit 1
  16. }
  17.  
  18. // asumsi angka adalah signed integer 32-bit dan leading zero tidak dihitung
  19. public static int hitungNomorBit(int angka, int nomorBit) {
  20. if (angka == 0 && nomorBit == 0) { // edge case untuk angka 0 dianggap sebagai 1 bit 0
  21. return 1;
  22. }
  23. int zeroCount = 0;
  24. int oneCount = 0;
  25. while (angka != 0) {
  26. if ((angka & 1) == 1) { // cek rightmost bit
  27. oneCount++;
  28. } else {
  29. zeroCount++;
  30. }
  31. angka >>>= 1; // unsigned right shift supaya bit kiri diisi 0
  32. }
  33. if (nomorBit == 0) {
  34. return zeroCount;
  35. } else if (nomorBit == 1) {
  36. return oneCount;
  37. } else {
  38. return 0; // tidak bisa return null karena return type di java harus seragam
  39. }
  40. }
  41. }
Success #stdin #stdout 0.12s 52596KB
stdin
Standard input is empty
stdout
1
3
0
31
1
1
32