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?

题目分析及思路

给定一个正整数范围,要求得到good number的个数。good number的定义是:对该数的各位数进行180度翻转,最后得到的数字与原数不同。这里,0,1,8翻转后还是本身,2,5,6,9翻转后可得不同的有效数字,剩余数字翻转则无效。可以先遍历这个范围的每一个数,并获得该数的各位数,最后只要确定各位数中没有3,4,7且有2,5,6,9即可确定该数为good number。

python代码

class Solution:

    def rotatedDigits(self, N: int) -> int:

        count = 0

        for n in range(2,N+1):

            digits = []

            while n:

                digit = n % 10

                digits.append(digit)

                n = n // 10

            if not (set(digits) & set([3,4,7])) and (set(digits) & set([2,5,6,9])):

                count += 1

        return count

                    

                

                

                

        

 

上一篇:CISC124 Lab Assignment 3: Mass Transit Optimizer Tool


下一篇:PTA的Python练习题(十五)