leetCode题解之旋转数字

1、题目描述

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.

题目是说将一个数字的每个数0-9旋转180度之后,如果旋转之后的数字和之前的数字不相等,则认为该数字是一个“好数”。旋转的规则如下:0,1,8 旋转之后不变,还是0,1,8. 2 旋转之后是5,5 旋转之后是2, 6和9 存在一样的关系。其余数 3,4,7旋转之后是不合法的。意思是一个数字中
如果有3,4,7三个钟的一个存在,则这个数一定不是好数。


2、题目分析

将一个输入的数转换成 string 格式,方便对每一个位数字做处理,转换使用 to_string函数,该函数时C++11中的函数。然后对 string中的每一位做处理,如果出现3,4,7则认为返回 false,认为这个数不是好数。如果是0,1,8则不做处理。是 2,5 ,6,9则分别转换。
最后将该string 转换为 int 型,使用 stoi函数,该函数也是c++11中的函数。
  题目要求,输入一个N,输出 1 - N中好数的个数。代码实现时 使用 一个子函数 完成判断,在大循环中累加好数的个数即可。

3、代码



 1  int rotatedDigits(int N) {
 2        
 3         // C++ 11中的 to_string 函数可以将数字转换为一个string。
 4         
 5         int n = 0;
 6         for (int i = 1; i <= N; i++ )
 7         {
 8            if( isGoodNum(i) )
 9                n++;
10         }
11         
12         return n;
13         
14     }
15     
16     bool isGoodNum(int i)
17     {
18         string s = to_string(i);
19         for(auto a = s.begin(); a != s.end(); a++ )
20             {
21                 if(*a == '3' || *a == '4' || *a == '7' )
22                     return false;
23                 
24                 switch(*a)
25                 {
26                     case '2':
27                         *a = '5';
28                         break;
29                     case '5':
30                         *a = '2';
31                         break;
32                     case '6':
33                         *a = '9';
34                         break;
35                     case '9':
36                         *a = '6';
37                         break;
38                     default:
39                         break;
40                 }
41             }
42         int newi = stoi(s);
43         
44         if(newi == i)
45             return false;
46         return true;
47         
48     }



pp
原文地址:https://www.cnblogs.com/wangxiaoyong/p/8657148.html