Problem Description
Determine the count of numbers in the range [1, n] that become a valid number and change value after each digit is rotated by 180 degrees. Only digits 0, 1, 8 remain unchanged, while 2, 5 and 6, 9 swap with each other; digits 3, 4, and 7 are invalid after rotation.
Key Insights
- A valid rotated number must only use the digits 0, 1, 8, 2, 5, 6, and 9.
- A number is "good" if it contains at least one digit (2, 5, 6, or 9) that changes upon rotation.
- If any digit in the number is 3, 4, or 7, the entire number becomes invalid.
- Iterating through each number from 1 to n and checking the validity and difference after rotation works efficiently given the constraints.
Space and Time Complexity
Time Complexity: O(n * d) where d is the number of digits in the number (in worst case, d is small due to n ≤ 10⁴).
Space Complexity: O(1)
Solution
The approach involves iterating from 1 to n and checking each digit in the number. A mapping is used to convert each digit to its rotated counterpart. If a digit is not present in the mapping (i.e., it is 3, 4, or 7), the number is discarded immediately. If the rotated number differs from the original, the number is counted as "good". This method leverages simple string operations or arithmetic digit extraction to perform the check.