73th LeetCode Weekly Contest Rotated Digits

X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. 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.

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,8,0是不会变的,2,5,6,9会变,其他变不了,那么我们只需要判断存在2,5,6,9这些就好了

 1 class Solution {
 2 public:
 3     int flag(string str){
 4         int len=str.length();
 5         if(len==1){
 6             for(int i=0;i<len;i++){
 7                 if(str[i]=='2'||str[i]=='5'||str[i]=='6'||str[i]=='9'){
 8                     return 1;
 9                 }else{
10                     return 0;
11                 }
12             }
13         }
14         int fit=0,fis=0;
15         for(int i=0;i<len;i++){
16             if(str[i]=='2'||str[i]=='5'||str[i]=='6'||str[i]=='9'){
17                   fit=1;
18             }else if(str[i]=='1'||str[i]=='0'||str[i]=='8'){
19                 fis=1;
20             }else{
21                 return 0;
22             }
23         }
24         if(fit==1){
25             return 1;
26         }else{
27             return 0;
28         }
29     }
30     int rotatedDigits(int N) {
31         int dis=0;
32         for(int i=1;i<=N;i++){
33             string Str="";
34             int num=i;
35             while(num){
36                 Str+=((num%10)+'0');
37                 num/=10;
38             }
39             if(flag(Str)){
40                   //  cout<<Str<<endl;
41                 dis++;
42             }
43             //cout<<Str<<" "<<i<<endl;
44         }
45         return dis;
46     }
47 };
原文地址:https://www.cnblogs.com/yinghualuowu/p/8503248.html