旋转的数字
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-N中不包含3,4,7,包含2,5,6,9的数字的个数。
重要测试用例:
1-10
459
1999-2010
思路:
3456
1)求 0-3000中的个数,n1
2)求3001-3400中的个数,n2
3)求3401-3450中的个数,n3
4)求3451-3456中的个数,n4
number= n1+ n2 + n3 + n4
难点:
高位为2,5,6,9和高位为0,1,8,Good的个数不同。
区分:
N | highIsGood | !highIsGood |
---|---|---|
0 | 0 | 1 |
1 | 0 | 2 |
2 | 1 | 3 |
3 | 1 | 3 |
4 | 1 | 3 |
5 | 2 | 4 |
6 | 3 | 5 |
7 | 3 | 5 |
8 | 3 | 6 |
9 | 4 | 7 |
代码
class Solution {
public:
int rotatedDigits(int N) {
// N [1, 10000], test case: 1-10, 1999-2010, 345, 467
int sum = 0, temp = N, high, unit;
bool highIsGood;
highIsGood = false;
unit = getUnit(temp);
high = temp / unit;
do
{
sum += getSum1(high, unit, highIsGood);
// test case: 328
if (3 == high || 4 == high || 7 == high)
break;
if(!highIsGood) highIsGood = (2 == high || 5 == high || 6 == high || 9 == high);
temp -= high * unit;
// test case: 200
if (temp == 0 && unit > 1 && highIsGood) sum += 1;
unit = getUnit(temp);
high = temp / unit;
}while (temp);
return sum;
}
int getUnit(int n){
int unit = 1;
while (n / 10){
n /= 10;
unit *= 10;
}
return unit;
}
int getSum1(int high, int unit, bool highIsGood){
switch (high){
case 1: return 1 * getSum2(unit, highIsGood) + highIsGood*(unit == 1);
case 2: return 2 * getSum2(unit, highIsGood) + (unit == 1);
case 3:
case 4: return 2 * getSum2(unit, highIsGood) + 1 * getSum2(unit, true);
case 5: return 2 * getSum2(unit, highIsGood) + 1 * getSum2(unit, true) + (unit == 1);
case 6: return 2 * getSum2(unit, highIsGood) + 2 * getSum2(unit, true) + (unit == 1);
case 7: return 2 * getSum2(unit, highIsGood) + 3 * getSum2(unit, true);
case 8: return 2 * getSum2(unit, highIsGood) + 3 * getSum2(unit, true) + highIsGood*(unit == 1);
case 9: return 3 * getSum2(unit, highIsGood) + 3 * getSum2(unit, true) + (unit == 1);
}
}
int getSum2(int unit, bool highIsGood){
if (1 == unit)
return highIsGood ? 1 : 0;
if (highIsGood) return 7 * getSum2(unit / 10, true);
return 4 * getSum2(unit / 10, true) + 3 * getSum2(unit / 10, false);
}
};