思路:
1、遍历从1---N+1的所有整数
2、将当前数字转化成字符串ch,只有所有字符都是list1中的字符,才满足旋转条件;
3、遍历字符串化后的数,将存在list1中的字符旋转,拼接给ans;
4、旋转后比较ch和ans,相等则res加1;
5、返回res。
1 class Solution(object): 2 def rotatedDigits(self, N): 3 """ 4 :type N: int 5 :rtype: int 6 """ 7 list1 = ['0', '1', '8', '2', '5', '6', '9'] 8 res = 0 9 # 遍历从1到N 10 for i in range(1, N+1): 11 # 整数字符串化,判断是否是旋转后不变化的数,是则进入下一趟循环 12 if set(str(i)) <= {'0', '1', '8'}: 13 print("旋转后不变的数:", i) 14 continue 15 # 转成字符串 16 ch = str(i) 17 ans = "" 18 # 转成set 19 setch = set(ch) 20 # 操作旋转后会变的数 21 if setch <= set(list1): 22 print("旋转后会变,且符合旋转条件的数:", i) 23 print("字符串化,且符合旋转条件的数:", ch) 24 # 遍历字符串,按要求将对应的数字旋转 25 for index, eng in enumerate(ch): 26 print("遍历字符串化后的数:当前字符为:", eng) 27 if eng in ['0', '1', '8']: 28 ans += eng 29 elif eng in ['2', '5'] and eng == '2': 30 ans += '5' 31 elif eng in ['2', '5'] and eng == '5': 32 ans += '2' 33 elif eng in ['6', '9'] and eng == '6': 34 ans += '9' 35 elif eng in ['6', '9'] and eng == '9': 36 ans += '6' 37 else: 38 ans += eng 39 print("旋转后的数:", ans) 40 # 不满足旋转条件的数跳过 41 else: 42 continue 43 # 判断旋转前后是否相等,即是不是“好数” 44 if ans != ch: 45 print("满足条件的好数:", ch) 46 res += 1 47 print() 48 return res 49 50 51 if __name__ == '__main__': 52 solution = Solution() 53 print(solution.rotatedDigits(2)) 54 print(solution.rotatedDigits(10))