LeetCode Solutions

728. Self Dividing Numbers

Time: $O(n\log n)$

Space: $O(1)$

			

class Solution {
 public:
  vector<int> selfDividingNumbers(int left, int right) {
    vector<int> ans;

    for (int num = left; num <= right; ++num)
      if (selfDividingNumbers(num))
        ans.push_back(num);

    return ans;
  }

 private:
  bool selfDividingNumbers(int num) {
    for (int n = num; n > 0; n /= 10)
      if (n % 10 == 0 || num % (n % 10) != 0)
        return false;
    return true;
  }
};
			

class Solution {
  public List<Integer> selfDividingNumbers(int left, int right) {
    List<Integer> ans = new ArrayList<>();

    for (int num = left; num <= right; ++num)
      if (dividingNumber(num))
        ans.add(num);

    return ans;
  }

  private boolean dividingNumber(int num) {
    for (int n = num; n > 0; n /= 10)
      if (n % 10 == 0 || num % (n % 10) != 0)
        return false;
    return true;
  }
}
			

class Solution:
  def selfDividingNumbers(self, left: int, right: int) -> List[int]:
    return [num for num in range(left, right + 1) if all(n != 0 and num % n == 0 for n in map(int, str(num)))]