We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid.
A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.(Note that the rotated number can be greater than the original number.)
Given a positive integer N, return the number of confusing numbers between 1 and N inclusive.
Example 1:
Input: 20
Output: 6
Explanation:
The confusing numbers are [6,9,10,16,18,19].
6 converts to 9.
9 converts to 6.
10 converts to 01 which is just 1.
16 converts to 91.
18 converts to 81.
19 converts to 61.
Example 2:
Input: 100
Output: 19
Explanation:
The confusing numbers are [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100].
自己比赛没来得及交,最后交的还是超时,改了改依旧超时,第一次是循环复杂度太大,第二次是字符串处理太耗时,最后参考大神的代码换long long过了,主体没怎么变,还是大神的代码思路清晰。我还需修炼啊。
大神的代码:
class Solution {
public:
int confusingNumberII(int N) {
n = N;
ans = 0;
search(0);
return ans;
}
private:
int n, ans;
void search(long long num) {
if (num > n) return;
if (num) {
if (rotate(num) != num) ++ ans;
}
if (num) search(num * 10);
search(num * 10 + 1);
search(num * 10 + 6);
search(num * 10 + 8);
search(num * 10 + 9);
}
long long rotate(long long x) {
long long y = 0;
for (; x; x /= 10) {
int k = x % 10;
switch (k) {
case 6: k = 9; break;
case 9: k = 6; break;
}
y = y * 10 + k;
}
return y;
}
};
我的代码:
class Solution {
public:
int h,res=0,M;
vector<int> rs = {0,1,6,8,9};
int dig(int n){
if(n==0) return 1;
int dig=0;
while(n){
h = n%10;
n/=10;
dig++;
}
return dig;
}
int change(int ans){
int r=0;
while(ans){
int base=ans%10;
if(base==6) base = 9;
else if(base==9) base = 6;
r = r*10+base;
ans/=10;
}
return r;
}
bool is(long long ans){
if(ans>M) return false;
int tmp = change(ans);
//cout<<ans<<" "<<tmp<<endl;
if(tmp==ans) return false;
return true;
}
int confusingNumberII(int N) {
int n = dig(N);
M = N;
backtracking(0,rs,n,0);
return res;
}
void backtracking(long long ans,vector<int> &rs,int n,int k){
if(is(ans)) res++;
if(k==n){
return ;
}
for(int i=0;i<5;i++){
if(ans==0&&i==0) continue;
ans = ans*10+rs[i];
backtracking(ans,rs,n,k+1);
ans/=10;
}
}
};