LeetCode Solutions

788. Rotated Digits

Time: $O(n\log n)$

Space: $O(1)$

			

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;
  }
};
			

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;
  }
}
			

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))