Skip to content
Problem 788 · LeetCode 788(opens in a new tab)

Rotated Digits

MediumDynamic programming

Turn a number upside down by rotating each of its digits half a turn. 0, 1 and 8 stay as they are. 2 and 5 swap, and so do 6 and 9. 3, 4 and 7 have no rotated form, so any number containing one of them cannot be turned.

Call a number good if every digit can be rotated and the result is a different number from the one you started with. Given n, count the good numbers from 1 to n.

Example 1

Input:  n = 12
Output: 5
Why:    2, 5, 6, 9 and 12 (which becomes 15); 10 and 11 stay the same
2 more examples and the constraints

Example 2

Input:  n = 7
Output: 3
Why:    2, 5 and 6; 1 is unchanged and 3, 4, 7 cannot rotate

Example 3

Input:  n = 30
Output: 15
Why:    the 20s add 20, 21, 22, 25, 26, 28 and 29

Constraints

  • 1 ≤ n ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every number's digitsO(n log n)
  2. DP on x / 10 and x % 10O(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 10,000Verdict
Check every number's digitsO(n log n)
Simple and fine here
DP on x / 10 and x % 10O(n)
Best; reuses smaller answers

n = the upper limit; log n counts the digits of a number.

Edge cases to test

  • n = 1. 1 rotates to itself, so the answer is 0.
  • Numbers made only of 0, 1, 8. 10, 11, 18, 80, 88 rotate fine but stay the same; they are not good.
  • A 0 at the end. 20 is good: 2 becomes 5 and 0 stays 0. The last-digit part, kind[0], must be 1, not 0.
  • One bad digit anywhere. 1,237 has a 3 and a 7, so it fails even though 1 and 2 rotate.
  • Upper limit. n = 10,000 contains no 2, 5, 6 or 9, so it adds nothing.

Common mistakes

  • Counting numbers made only of 0, 1 and 8, which rotate into themselves.
  • Treating 0 as "no digit" and giving kind[0] the value 0, which wrongly rejects 20, 50 and so on.
  • Thinking 6 and 9 are the only changing digits and forgetting the 2 and 5 swap.

How to talk through it

  1. 1Clarify. Does the rotated number have to differ? Is 0 counted? Is the range 1 to n inclusive?
  2. 2Sort the digits. Three groups: broken (3, 4, 7), unchanged (0, 1, 8), changing (2, 5, 6, 9).
  3. 3Give the simple check. For each number, scan its digits with two flags.
  4. 4Reuse smaller answers. Kind of x comes from the kinds of x / 10 and x % 10 in O(1).
  5. 5Test out loud. Run n = 1, n = 12 and a number like 20 that ends in 0.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?