Java Solution beats 99.93 % time
The idea is to maintain an array of the digits of N (actually only the first half of them) and increase them to form valid palindromes. Then we check if they ar
The idea is to maintain an array of the digits of N (actually only the first half of them) and increase them to form valid palindromes. Then we check if they are also a prime number.\n\nThe solution is arguably a bit convoluted because of all the low-level operations, but fast due to the fact that it doesn\'t rely on string operations.\n\nI also added skipping even-digit palindromes after I read that they cannot be prime numbers ( -_-\' ), which makes it even faster. \n\n````\nclass Solution {\n    public int primePalindrome(int N) {\n        if (N <= 2) return 2;\n        if (N > 7 && N <= 11) return 11;\n\n        int digitsCount = (int)Math.floor(Math.log10(N)) + 1; // number of digits of N\n        if (digitsCount % 2 == 0) { N = (int)Math.pow(10, digitsCount); digitsCount++; } // skip even-digits palindromes\n        int[] digits = new int[(digitsCount + 1) / 2]; // array of half the length of the number of digits\n        // put the first half of the digits of N in the array\n        int n = N, count = 0;\n        while (n > 0) {\n            if (++count > (digitsCount + 1) / 2) digits[digitsCount - count] = n % 10;\n            n /= 10;\n        }\n\n        while (true) {\n            // create a palindrome number based on the current digits and check if it\'s a prime\n            int number = 0;\n            for (int i = 0; i < digitsCount; i++) {\n                int index = i < digits.length ? i : digitsCount - i - 1;\n                number = number * 10 + digits[index];\n            }\n            if (number >= N && isPrime(number)) return number;\n            \n            // if not, increment the digits to generate the next valid palindrome\n            boolean increment = true;\n            for (int i = digits.length - 1; increment && i >= 0; i--) {\n                if (i == 0) {\n                    if ((digits[0] & 1) != 1) digits[0]++;\n                    else if (digits[0] == 9) {\n                        digitsCount += 2;\n                        digits = new int[(digitsCount + 1) / 2];\n                        digits[0] = 1;\n                    } else {\n                        digits[0] += 2;\n                    }\n                } else if (digits[i] == 9) {\n                    digits[i] = 0;\n                    increment = true;\n                } else {\n                    digits[i] += 1;\n                    increment = false;\n                }\n            }\n        }\n    }\n    \n    private boolean isPrime(int n) {\n        if (n == 1) return false;\n        \n        for (int i = 2; i <= Math.sqrt(n); i++) {\n            if (n % i == 0) return false;\n        }\n        \n        return true;\n    }\n}\n````
[]