Rotated Digits Problem
Description
LeetCode Problem 788.
An integer x is a good 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. For example:
- 0, 1, and 8 rotate to themselves,
- 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),
- 6 and 9 rotate to each other, and
- the rest of the numbers do not rotate to any other number and become invalid.
Given an integer n, return the number of good integers in the range [1, n].
Example 1:
Input: n = 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.
Example 2:
Input: n = 1
Output: 0
Example 3:
Input: n = 2
Output: 1
Constraints:
- 1 <= n <= 10^4
Solution
Approach: Check Each Number's Digits
Rotating a number rotates each digit on its own, so whether a number is good depends only on which digits it contains. Sort the ten digits into three groups:
3,4,7are invalid: they are not digits after rotation, so any number containing one is not valid.0,1,8stay the same.2,5,6,9change into a different digit.
A number is good when it has no invalid digit and at least one changing digit. If every digit is from 0, 1, 8, the rotated number equals the original, so it does not count (that is why 1 and 10 are not good). If some digit changes, the rotated number differs from the original in that position, so it is different.
For every x from 1 to n, peel off its digits with x % 10 and x / 10: return false as soon as an invalid digit appears, and remember whether any digit changes.
Complexity: O(n log n) time, since each of the n numbers has O(log n) digits, and O(1) space.
class Solution:
def rotatedDigits(self, n: int) -> int:
return sum(1 for x in range(1, n + 1) if self.is_good(x))
def is_good(self, x: int) -> bool:
changes = False # does some digit turn into a different digit?
while x > 0:
digit = x % 10
if digit in (3, 4, 7): # these digits are invalid after rotation
return False
if digit in (2, 5, 6, 9): # these digits change; 0, 1 and 8 stay the same
changes = True
x //= 10
return changes