X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. 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.
Now given a positive number N, how many numbers X from 1 to N are good?
Example:
Input: 10
Output: 4
Explanation:
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
思路:只要这个数字有一位是{2,5,6,9}中的一个,并且这个数字不包含{3,4,7}那么这个数就是好数。
class Solution {
public:
bool check(int n) {
if (n == 2 || n == 5 || n == 6 || n == 9) return true;
return false;
}
bool check2(int n) {
if (n == 3 || n == 4 || n == 7) return true;
return false;
}
bool judge(int n) {
int mark1 = 0;
int mark2 = 0;
while (n > 0) {
int x = n%10;
if (check(x)) mark1 = 1;
if (check2(x)) mark2 = 1;
n /= 10;
}
if (mark1 && !mark2) return true;
return false;
}
int rotatedDigits(int N) {
int ans = 0;
for (int i = 1; i <= N; ++i) {
if (judge(i)) {
//cout << i << endl;
ans++;
}
}
return ans;
}
};