# C#LeetCode刷题之#788-旋转数字（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.  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?

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].

```public class Program {

public static void Main(string[] args) {
var N = 10;

var res = RotatedDigits(N);
Console.WriteLine(res);

N = 68;

res = RotatedDigits2(N);
Console.WriteLine(res);

}

private static int RotatedDigits(int N) {
var res = 0;
for(int i = 0; i < N; i++) {
if(IsGoodDigit(i + 1)) res++;
}
return res;
}

private static bool IsGoodDigit(int n) {
//先给出映射列表
var dic = new Dictionary<char, char>() {
{'0', '0'},
{'1', '1'},
{'2', '5'},
{'5', '2'},
{'6', '9'},
{'8', '8'},
{'9', '6'}
};
//创建 StringBuilder 加速字符串运算
var sb = new StringBuilder(n.ToString());
//循环计算所有字符串
for(var i = 0; i < sb.Length; i++) {
//不包含时，根据题意直接返回 false
if(!dic.ContainsKey(sb[i])) return false;
else {
//进行“旋转”
sb[i] = dic[sb[i]];
}
}
//跟原串不一样时返回 true
return n.ToString() != sb.ToString();
}

private static int RotatedDigits2(int N) {
var res = 0;
for(int i = 0; i < N; i++) {
res += IsGoodDigit2(i + 1) ? 1 : 0;
}
return res;
}

private static bool IsGoodDigit2(int n) {
//转换成字符串
var bit = n.ToString();
//包含3，4，7时，直接判定 false
//因为旋转后无效了
if(bit.Contains('3') || bit.Contains('4') || bit.Contains('7'))
return false;
//包含2，5，6，9时，直接判定 true
//因为旋转后值肯定变了，并且代码执行到此处
//说明原串中不包含3、4、7，不可能会无效
if(bit.Contains('2') || bit.Contains('5') || bit.Contains('6') || bit.Contains('9')) {
return true;
}
//其它所有情况直接判定 false 即可
//包含 0，1，8 却不能被上述代码命中
//肯定不是好数
return false;
}

}```

```4
28```