Rotated Digits

You want to find the number of “good” integers within a given range, where “good” is defined by specific rules of digit rotation.

We can solve this by iterating through the range and checking each number to see if it meets the conditions. Here’s a possible solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def rotatedDigits(self, n: int) -> int:
        # Define the valid transformations
        valid_transforms = {'0': '0', '1': '1', '8': '8', '2': '5', '5': '2', '6': '9', '9': '6'}
        count = 0

        for i in range(1, n + 1):
            str_i = str(i)
            transformed = ""
            is_good = True

            # Rotate each digit and check if the rotation is valid
            for digit in str_i:
                if digit not in valid_transforms:
                    is_good = False
                    break
                transformed += valid_transforms[digit]

            # If the rotation is valid and the number is changed, it's a good number
            if is_good and transformed != str_i:
                count += 1

        return count

This code iterates through all the integers from 1 to n, rotating the digits as defined, and checks if the number changes and remains valid after the rotation. The final count of good numbers is returned.