Confusing Number II - Problem

A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.

We can rotate digits of a number by 180 degrees to form new digits:

  • When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively
  • When 2, 3, 4, 5, 7 are rotated 180 degrees, they become invalid

Note: After rotating a number, we can ignore leading zeros. For example, after rotating 8000, we have 0008 which is considered as just 8.

Given an integer n, return the number of confusing numbers in the inclusive range [1, n].

Input & Output

Example 1 — Small Range
$ Input: n = 20
Output: 6
💡 Note: Confusing numbers in [1,20]: 6→9, 9→6, 10→01=1, 16→91, 18→81, 19→61. Count = 6.
Example 2 — Single Digit
$ Input: n = 9
Output: 2
💡 Note: Only 6→9 and 9→6 are confusing in range [1,9]. Numbers 0,1,8 rotate to themselves.
Example 3 — Edge Case
$ Input: n = 1
Output: 0
💡 Note: Number 1 rotates to 1 (same), so it's not confusing. No confusing numbers in [1,1].

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Confusing Number II: Rotation RulesValid Digits{0,1,6,8,9}Invalid Digits{2,3,4,5,7}Rotation Map6↔9, 8→8Examples:68925→ 9 ✓→ 8 ❌→ 6 ✓invalidCount confusing numbers: rotation ≠ originalFor n=20: answer is 6 (numbers: 6,9,10,16,18,19)
Understanding the Visualization
1
Input Range
Check all numbers from 1 to n
2
Rotation Rules
0→0, 1→1, 6→9, 8→8, 9→6, others invalid
3
Count Different
Count numbers where rotation ≠ original
Key Takeaway
🎯 Key Insight: Only generate numbers using digits {0,1,6,8,9}, then count those where rotation differs from original
Asked in
Google 15 Facebook 8
23.0K Views
Medium Frequency
~35 min Avg. Time
892 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