Given A and B, count the numbers N such that A ≤ N ≤ B and N is a palindrome.
Input:
First line contains T, the number of testcases. Each testcase consists of two integers A and B in one line.
Output:
For each testcase, print the required answer in one line.
Constraints:
1 ≤ T ≤ 10
0 ≤ A ≤ B ≤ 10^5
private static boolean[] isPalindrome = isPalindrome();
public static void main(String args[] ) throws NumberFormatException,
IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
int totalTestCase = Integer.parseInt(reader.readLine());
StringBuilder outputPalindromeCount = new StringBuilder();
for (int i = 0; i < totalTestCase; i++) {
String[] input=reader.readLine().split(" ");
int startNo = Integer.parseInt(input[0]);
int endNo = Integer.parseInt(input[1]);
int totalFoundPalindrome = getPalindromeCount(startNo, endNo);
outputPalindromeCount.append(totalFoundPalindrome + "\n");
}
System.out.println(outputPalindromeCount);
}
private static int getPalindromeCount(int startNo, int endNo) {
int totalPalindromeFound = 0;
for (int i = startNo; i <= endNo ; i++ ){
if(isPalindrome[i]){
totalPalindromeFound++;
}
}
return totalPalindromeFound;
}
private static boolean[] isPalindrome() {
boolean[] isPalindrome = new boolean[100001];
Arrays.fill(isPalindrome, 0, 10, true);
for (int i = 10; i <= 100000; i++) {
if (checkForPalindrome(i)) {
isPalindrome[i] = true;
}
}
return isPalindrome;
}
private static boolean checkForPalindrome(int i) {
int divNo = 1;
while (i / divNo >= 10) {
divNo = divNo * 10;
}
while (i != 0) {
int startingDigit = i / divNo;
int lastDigit = i % 10;
if (startingDigit != lastDigit) {
return false;
}
i = (i % divNo) / 10;
divNo = divNo / 100;
}
return true;
}
}
For this input:
6 0 0 1 1 1 10 1 9 1 1000 1000 100000
this code took 0.18 seconds. It's taking almost 0.18-0.20 seconds for various sets of input (link of all inputs and time).
What are the other Efficient way of checking palindromes (not just a way of conversion to a string and then check but really efficient)?
How could have I optimized the above code further (apart from BitSet which is a trade off for runtime)?