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.
题目大意:给定一个数,翻转其每一位数,仍然可以成为一个有效的数字,而且不与原来的数重复,我们认为这个数是一个好数,求给定区间内好数的数目。
分析: 对于每一个数来说,我们假设数子为abcd,可以将数子拆分为abc,d两部分。如果abc翻转完后还是abc,d翻转完后还是d,那么abcd翻转完后与原来的数一致,当abc,d两部分只有任意一个翻转后不是有效数字,abcd就翻转后就无效,只要有一个出现翻转后有效,那么abcd就可以称为好数。因此我们可以使用动态规划进行解题。
建立状态转移方程:
建立dp[n+1],0 为无效,1为翻转后仍为原数,2表示翻转后与原数不同 。
dp[i] : 将有dp[i/10] 和dp[i%10]共同决定。
代码:
int dp[] = new int[N+1];
int res = 0;
for(int i = 0 ; i < N+1;i++) {
if(i < 10) {
if (i == 0 || i == 1 || i == 8) dp[i] = 1;
else if(i == 2 || i == 5 || i == 6 || i == 9) {
res++;
dp[i] =2;
}
}else {
int a = dp[i/10],b = dp[i%10];
if(a == 1 && b == 1) dp[i] = 1;
else if((a >1 && b >=1) ||( b >1 && a>=1)) {
dp[i] = 2;
res++;
}
}
}
return res;
当然还可以直接暴力循环,将每一位数字转为字符串,然后逐个验证就行。