|
| 1 | +# Rotated Digits (Medium) |
| 2 | + |
| 3 | +**Problem ID:** 788 |
| 4 | +**Date:** 2026-05-02 |
| 5 | +**Link:** https://leetcode.com/problems/rotated-digits/ |
| 6 | + |
| 7 | +## Approach |
| 8 | + |
| 9 | +To solve the "Rotated Digits" problem, we need to determine how many integers in the range [1, n] are "good" based on the rotation rules provided. A number is classified as "good" if, after rotating each of its digits by 180 degrees, it results in a valid number that is different from the original number. |
| 10 | + |
| 11 | +### Approach: |
| 12 | + |
| 13 | +1. **Understanding Digit Rotation**: |
| 14 | + - We first identify which digits are valid after rotation: |
| 15 | + - Valid digits: 0, 1, 8 (remain the same) |
| 16 | + - Valid pairs: 2 ↔ 5, 6 ↔ 9 |
| 17 | + - Invalid digits: 3, 4, 7 (become invalid) |
| 18 | + - A "good" number must contain at least one of the digits that change (2, 5, 6, or 9) and must not consist solely of valid digits that remain unchanged (0, 1, 8). |
| 19 | + |
| 20 | +2. **Iterate Through the Range**: |
| 21 | + - We will iterate through each number from 1 to n and check its digits. |
| 22 | + - For each number, we will convert it to its string representation to easily access each digit. |
| 23 | + |
| 24 | +3. **Check Each Digit**: |
| 25 | + - For each digit in the number: |
| 26 | + - If any digit is invalid (3, 4, 7), we can skip to the next number. |
| 27 | + - If we encounter a digit that changes (2, 5, 6, or 9), we mark this number as "good". |
| 28 | + |
| 29 | +4. **Count Good Numbers**: |
| 30 | + - Maintain a counter to keep track of how many "good" numbers we find during our iteration. |
| 31 | + |
| 32 | +### Data Structures: |
| 33 | +- We primarily use a simple integer counter to track the number of good numbers. |
| 34 | +- String representation of numbers allows for easy digit access and checking. |
| 35 | + |
| 36 | +### Complexity: |
| 37 | +- **Time Complexity**: O(n * d), where n is the input number and d is the number of digits in n. In the worst case, d is log10(n), making the complexity effectively O(n) for the upper limit of n (10,000). |
| 38 | +- **Space Complexity**: O(1), as we only use a few variables to store counts and check digits. |
| 39 | + |
| 40 | +By following this structured approach, we can efficiently determine the count of good integers in the specified range. |
0 commit comments