Skip to content

788. Rotated Digits 👎

  • Time: $O(n\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
 public:
  int rotatedDigits(int N) {
    int ans = 0;

    for (int i = 1; i <= N; ++i)
      if (isGoodNumber(i))
        ++ans;

    return ans;
  }

 private:
  bool isGoodNumber(int i) {
    bool isRotated = false;

    for (const char c : to_string(i)) {
      if (c == '0' || c == '1' || c == '8')
        continue;
      if (c == '2' || c == '5' || c == '6' || c == '9')
        isRotated = true;
      else
        return false;
    }

    return isRotated;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int rotatedDigits(int N) {
    int ans = 0;

    for (int i = 1; i <= N; ++i)
      if (isGoodNumber(i))
        ++ans;

    return ans;
  }

  private boolean isGoodNumber(int i) {
    boolean isRotated = false;

    for (final char c : String.valueOf(i).toCharArray()) {
      if (c == '0' || c == '1' || c == '8')
        continue;
      if (c == '2' || c == '5' || c == '6' || c == '9')
        isRotated = true;
      else
        return false;
    }

    return isRotated;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def rotatedDigits(self, N: int) -> int:
    def isGoodNumber(i: int) -> bool:
      isRotated = False

      for c in str(i):
        if c == '0' or c == '1' or c == '8':
          continue
        if c == '2' or c == '5' or c == '6' or c == '9':
          isRotated = True
        else:
          return False

      return isRotated

    return sum(isGoodNumber(i) for i in range(1, N + 1))