X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.
Now given a positive numberN
, how many numbers X from1
toN
are good?
class Solution {
public int rotatedDigits(int N) {
int res = 0;
for(int i = 1; i <= N; i++){
if(isGoodNumber(i))
res++;
}
return res;
}
public boolean isGoodNumber(int N) {
String n = String.valueOf(N);
char[] cs = n.toCharArray();
for(int i = 0; i < cs.length; i++) {
if(cs[i] == '0' || cs[i] == '1' || cs[i] == '8')
continue;
if(cs[i] == '6') {
cs[i] = '9';
} else if(cs[i] == '9') {
cs[i] = '6';
} else if(cs[i] == '2') {
cs[i] = '5';
} else if(cs[i] == '5') {
cs[i] = '2';
} else {
return false;
}
}
return Integer.parseInt(String.valueOf(cs)) != N;
}
}