public class Reversible {
final int max;
final int numReversible;
public Reversible(int max){
this.max = max;
this.numReversible = this.countReversible();
}
private int countReversible(){
if (numReversible > 0){
return numReversible;
}
int cnt = 0;
for (int i=11;i<=max;i++){
if (reversible(i)) {
cnt++;
}
}
return cnt;
}
private boolean reversible(int n){
return allOdd(reverse(n));
}
private boolean allOdd(int n){
while (n > 0){
int remainder = n % 2;
if (remainder == 0) return false;
n = n / 10;
}
return true;
}
private int reverse(Integer n){
char[] digits = n.toString().toCharArray();
char[] rev = new char[digits.length];
for (int i=digits.length-1;i>=0;i--){
rev[i] = digits[digits.length -i-1];
}
return n + Integer.parseInt(String.valueOf(rev));
}
}
Wednesday, May 20, 2009
JavaOne Talk: Reversible Numbers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment