题目:
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 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.
Note:
- N will be in range
[1, 10000]
.
思路:
刚开始做的时候以为有什么更好的算法,不用遍历就可以通过公式获得答案,后来发现还是需要一个一个试,所以就没有什么算法方面需要讲的了。
唯一需要注意的是,1,10等不符合题目要求,因为它们rotate之后还是本身,所以我们在检测的过程中就要求数字中至少含有一个2,5,6,9,并且里面不能含有3,4,7。
代码:
class Solution {
public:
int rotatedDigits(int N) {
int count = 0;
for (int i = 2; i <= N; ++i) {
count += isValid(i);
}
return count;
}
private:
bool isValid(int N) {
// Valid if N contains at least one 2, 5, 6, 9, and no 3, 4 or 7s
bool validFound = false;
while (N > 0) {
if (N % 10 == 2) validFound = true;
if (N % 10 == 5) validFound = true;
if (N % 10 == 6) validFound = true;
if (N % 10 == 9) validFound = true;
if (N % 10 == 3) return false;
if (N % 10 == 4) return false;
if (N % 10 == 7) return false;
N = N / 10;
}
return validFound;
}
};