Rotated Digits - Problem

An integer x is a good number 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:

  • 0, 1, and 8 rotate to themselves
  • 2 and 5 rotate to each other
  • 6 and 9 rotate to each other
  • The rest of the numbers (3, 4, 7) 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].

Input & Output

Example 1 — Basic Case
$ Input: n = 10
Output: 4
💡 Note: Numbers 1-10: Good numbers are 2 (→5), 5 (→2), 6 (→9), 9 (→6). Numbers like 1 (→1) and 8 (→8) are same after rotation, so not good.
Example 2 — Smaller Range
$ Input: n = 1
Output: 0
💡 Note: Only number 1, which rotates to itself (1→1), so it's not different. No good numbers.
Example 3 — Larger Range
$ Input: n = 25
Output: 9
💡 Note: Good numbers are: 2, 5, 6, 9, 12, 15, 16, 19, 20. Numbers like 25 (→52) are good, but 22 (→55) contains invalid digits after 10.

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Rotated Digits - Digit Classification INPUT n = 10 Rotation Rules: Valid Rotations 0 --> 0 1 --> 1 8 --> 8 2 --> 5 5 --> 2 6 --> 9 9 --> 6 Invalid Digits 3, 4, 7 --> X Check Range [1, 10]: 1 2 3 4 5 6 7 8 9 10 ALGORITHM STEPS 1 Classify Digits Group: same, change, invalid Same: 0,1,8 Change: 2,5,6,9 Invalid: 3,4,7 2 For Each Number Check each digit classification 3 Validate Number Must have 2,5,6,9 & no 3,4,7 4 Count Good Numbers Increment if valid & different Example Checks: 2-->5 OK 5-->2 OK 6-->9 OK 9-->6 OK 3-->X 4-->X 7-->X 1-->1 same FINAL RESULT Number Analysis: 1-->1 2-->5 3-->X 4-->X 5-->2 6-->9 7-->X 8-->8 9-->6 10-->01 Good Numbers Found: 2 rotates to 5 5 rotates to 2 6 rotates to 9 9 rotates to 6 OUTPUT 4 4 good numbers in [1,10] Key Insight: A number is "good" if: (1) All digits are valid (0,1,2,5,6,8,9) AND (2) At least one digit changes when rotated (must contain 2,5,6, or 9). Numbers with only 0,1,8 are valid but NOT good (same after rotation). Time Complexity: O(n * log(n)) where log(n) is the number of digits. Space: O(1). TutorialsPoint - Rotated Digits | Optimized Digit Classification Approach
Asked in
Google 15 Amazon 8
32.0K Views
Medium Frequency
~15 min Avg. Time
850 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