Rotated Digits - Problem
Rotated Digits is a fascinating number manipulation problem that explores what happens when we rotate each digit by 180 degrees.

Imagine holding a calculator upside down - some digits still look like valid numbers, while others become unreadable! A number is considered "good" if:

1. After rotating each digit 180°, we get a valid number
2. The rotated number is different from the original

The rotation rules are:
0, 1, 8 → rotate to themselves
2 ↔ 5 rotate to each other
6 ↔ 9 rotate to each other
3, 4, 7 → become invalid when rotated

For example, 25 becomes 52 (different and valid), so it's good. But 11 becomes 11 (same number), so it's not good.

Goal: Count how many good numbers exist in the range [1, n].

Input & Output

example_1.py — Basic Case
$ Input: n = 10
Output: 4
💡 Note: Good numbers from 1 to 10 are: 2 (→5), 5 (→2), 6 (→9), 9 (→6). Numbers like 1, 8 stay the same when rotated, and 3, 4, 7 become invalid.
example_2.py — Larger Range
$ Input: n = 857
Output: 247
💡 Note: Count all good numbers from 1 to 857. This includes multi-digit numbers like 25 (→52), 69 (→96), etc., as long as they contain at least one changing digit and no invalid digits.
example_3.py — Edge Case
$ Input: n = 2
Output: 1
💡 Note: Only number 2 is good (rotates to 5). Number 1 rotates to itself, so it's not good.

Constraints

  • 1 ≤ n ≤ 104
  • All inputs are positive integers
  • Time limit: 1 second per test case

Visualization

Tap to expand
Digital Display Rotation Challenge25Original DisplayRotate 180°52Rotated DisplayGOOD!Rotation Examples:25693???Algorithm Steps1Check each digit for validity (no 3,4,7)2Ensure at least one changing digit (2,5,6,9)3If both conditions met, number is good4Count all good numbers in range [1, n]
Understanding the Visualization
1
Identify Digit Types
Categorize each digit: Invalid (3,4,7), Changing (2,5,6,9), or Same (0,1,8)
2
Check Validity
If any digit is invalid (3,4,7), the number can't be good
3
Ensure Difference
The number must contain at least one changing digit (2,5,6,9) to be different when rotated
4
Count Good Numbers
Increment counter for each number that passes both validity and difference checks
Key Takeaway
🎯 Key Insight: A number is good if it has at least one changing digit (2,5,6,9) and no invalid digits (3,4,7) - no need to actually construct the rotated number!
Asked in
Google 15 Amazon 8 Microsoft 5 Apple 3
28.9K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen