fork(5) download
  1. import java.util.Arrays;
  2.  
  3. class Ideone {
  4. public static final int[] gaps(int n) {
  5. // The number of gaps is the number of one bits minus one.
  6. final int[] result = new int[Math.max(0, Integer.bitCount(n) - 1)];
  7.  
  8. // Remove the last one bit and all bits after to get to first gap.
  9. n >>>= Integer.numberOfTrailingZeros(n) + 1;
  10.  
  11. for (int i = result.length - 1; i >= 0; i--) {
  12. final int gapSize = Integer.numberOfTrailingZeros(n);
  13. result[i] = gapSize;
  14. // Remove the last one bit and all bits after to get to next gap.
  15. n >>>= gapSize + 1;
  16. }
  17.  
  18. return result;
  19. }
  20.  
  21. // Driver program
  22. public static void main(final String[] args) {
  23. final int n = 1041;
  24. System.out.println(Integer.toBinaryString(n));
  25. System.out.println(Arrays.toString(gaps(n)));
  26. }
  27. }
Success #stdin #stdout 0.09s 47032KB
stdin
Standard input is empty
stdout
10000010001
[5, 3]