fork(4) download
  1. public class Main
  2. {
  3. public static void main(String[] args) {
  4. for (int i = 65535; i < 65545; i++) {
  5. System.out.println(
  6. i + ": " + getBinaryPalindrom(i) + " = " + Integer.toBinaryString(getBinaryPalindrom(i)));
  7. }
  8. }
  9.  
  10. public static int getBinaryPalindrom(int N) {
  11. if (N < 4) {
  12. switch (N) {
  13. case 1:
  14. return 0;
  15. case 2:
  16. return 1;
  17. case 3:
  18. return 3;
  19. }
  20. throw new IndexOutOfBoundsException("You need to supply N >= 1");
  21. }
  22. // second highest to keep the right length (highest is always 1)
  23. final int bitAfterHighest = (N >>> (Integer.SIZE - Integer.numberOfLeadingZeros(N) - 2)) & 1;
  24. // now remove the second highest bit to get the left half of our palindrom
  25. final int leftHalf = (((N >>> (Integer.SIZE - Integer.numberOfLeadingZeros(N) - 1)) & 1) << (Integer.SIZE -
  26. Integer.numberOfLeadingZeros(N) - 2)) | ((N << (Integer.numberOfLeadingZeros(N) + 2)) >>> (Integer.numberOfLeadingZeros(N) + 2));
  27. // right half is just the left reversed
  28. final int rightHalf = Integer.reverse(leftHalf);
  29. if (Integer.numberOfLeadingZeros(leftHalf) < Integer.SIZE / 2) {
  30. throw new IndexOutOfBoundsException("To big to fit N=" + N + " into an int");
  31. }
  32. if (bitAfterHighest == 0) {
  33. // First uneven-length palindromes
  34. return (leftHalf << (Integer.SIZE - Integer.numberOfLeadingZeros(leftHalf)) - 1) | (rightHalf
  35. >>> Integer.numberOfTrailingZeros(rightHalf));
  36. } else {
  37. // Then even-length palindromes
  38. return (leftHalf << (Integer.SIZE - Integer.numberOfLeadingZeros(leftHalf))) | (rightHalf
  39. >>> Integer.numberOfTrailingZeros(rightHalf));
  40. }
  41. }
  42. }
Success #stdin #stdout 0.05s 711168KB
stdin
Standard input is empty
stdout
65535: 1073741823 = 111111111111111111111111111111
65536: 1073741825 = 1000000000000000000000000000001
65537: 1073774593 = 1000000000000001000000000000001
65538: 1073823745 = 1000000000000010100000000000001
65539: 1073856513 = 1000000000000011100000000000001
65540: 1073881089 = 1000000000000100010000000000001
65541: 1073913857 = 1000000000000101010000000000001
65542: 1073963009 = 1000000000000110110000000000001
65543: 1073995777 = 1000000000000111110000000000001
65544: 1074008065 = 1000000000001000001000000000001