这里给出两种方法
方法一,逐个数字逐位判定,速度有点慢,但是很好理解
1 class Solution 2 { 3 public: 4 int rotatedDigits(int N) 5 { 6 unordered_set<int> unvalid{3,4,7}; 7 unordered_set<int> change{2,5,6,9}; 8 int count=0; 9 for(int i=2;i<=N;i++) 10 { 11 int cur=i; 12 int flag=0; 13 while(cur) 14 { 15 int last=cur%10; 16 if(unvalid.find(last)!=unvalid.end()) 17 { 18 flag=0; 19 break; 20 } 21 if(change.find(last)!=change.end()) 22 flag=1; 23 cur/=10; 24 } 25 count+=flag; 26 } 27 return count; 28 } 29 };
方法二,利用前面的判定结果,加快判定速度
1 class Solution 2 { 3 public: 4 int rotatedDigits(int N) 5 { 6 vector<int> judge(N+1,0); 7 int count=0; 8 for(int i=0;i<=N;i++) 9 { 10 if(i<10) 11 { 12 if(i==0||i==1||i==8) 13 judge[i]=1; 14 else if(i==3||i==4||i==7) 15 judge[i]=0; 16 else 17 { 18 judge[i]=2; 19 count++; 20 } 21 } 22 else 23 { 24 int pre=judge[i/10]; 25 int last=judge[i%10]; 26 if(pre==1&&last==1) 27 judge[i]=1; 28 else if(pre+last>2) 29 { 30 judge[i]=2; 31 count++; 32 } 33 else 34 judge[i]=0; 35 } 36 } 37 return count; 38 } 39 };