Skip to content

728. Self Dividing Numbers 👍

  • 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
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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;
  }
}
1
2
3
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)))]