Skip to content

Instantly share code, notes, and snippets.

@canwe
Forked from matyb/PalindromeGenerator.java
Created August 30, 2013 12:21
Show Gist options
  • Save canwe/6389314 to your computer and use it in GitHub Desktop.
Save canwe/6389314 to your computer and use it in GitHub Desktop.
package math.recreational.generators;
import java.util.Iterator;
public class PalindromeGenerator implements Iterator<Long> {
private Long current = 0l;
@Override
public boolean hasNext() {
return current >= 0;
}
@Override
public Long next() {
if (!hasNext()) {
throw new ArithmeticException(current.getClass().getSimpleName()
+ " is not large enough to represent the next palindrome.");
}
Long tempValue = current;
calculateNextValue();
return tempValue;
}
private void calculateNextValue() {
try {
String s = String.valueOf(current);
int length = s.length();
int half = length / 2;
if (isAllNines(s)) {
current += 2l;
} else if (length % 2 != 0) {
String firstHalf = s.substring(0, half)
+ s.substring(half, half + 1);
String incrementedHalf = String
.valueOf(Long.valueOf(firstHalf) + 1l);
String reversedHalf = reverse(incrementedHalf
.substring(0, half));
current = Long.valueOf(incrementedHalf + reversedHalf);
} else {
String firstHalf = String.valueOf(Long.valueOf(s.substring(0,
half)) + 1);
current = Long.valueOf(firstHalf + reverse(firstHalf));
}
} catch (NumberFormatException x) {
current = Long.MIN_VALUE;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private boolean isAllNines(String s) {
return s.replace("9", "").isEmpty();
}
private String reverse(String firstHalf) {
return new StringBuffer(firstHalf).reverse().toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment