package com.pg.iterableRng;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RangePalindromeIterator implements Iterator<Integer> {
int lastReturned;
int max;
public RangePalindromeIterator(int min, int max) {
this.lastReturned = isPalindrome(min) ? min : nextPal(min);
this.max = max;
}
@Override
public boolean hasNext() {
return (lastReturned < max);
}
@Override
public Integer next() {
if(!hasNext()) throw new NoSuchElementException();
int res = lastReturned;
lastReturned = nextPal(++lastReturned);
return Integer.valueOf(res);
}
int nextPal(final int n){
int res = n;
while (!isPalindrome(res)){
res++;
}
return res;
}
static boolean isPalindrome(int N){
return N == numReverse(N);
}
static int numReverse(int N){
int res = 0;
if (N == 0) {
return 0;
}
if (N > 0){
res = positiveNumReverse(N);
}else{
res = -positiveNumReverse(-N);
}
return res;
}
static int positiveNumReverse(int N){
int res = 0;
while ( N > 0 ){
res *= 10;
res += N % 10;
N = N / 10;
}
return res;
}
}