For each number in the range, check if all its digits are nonzero and divide the number itself. If so, include it in the answer. This is efficient enough for the given constraints.
#include<vector>usingnamespace std;
classSolution {
public: vector<int> selfDividingNumbers(int left, int right) {
vector<int> res;
for (int n = left; n <= right; ++n) {
int x = n, ok =1;
while (x) {
int d = x %10;
if (d ==0|| n % d !=0) { ok =0; break; }
x /=10;
}
if (ok) res.push_back(n);
}
return res;
}
};
import java.util.*;
classSolution {
public List<Integer>selfDividingNumbers(int left, int right) {
List<Integer> res =new ArrayList<>();
for (int n = left; n <= right; ++n) {
int x = n;
boolean ok =true;
while (x > 0) {
int d = x % 10;
if (d == 0 || n % d != 0) { ok =false; break; }
x /= 10;
}
if (ok) res.add(n);
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funselfDividingNumbers(left: Int, right: Int): List<Int> {
val res = mutableListOf<Int>()
for (n in left..right) {
var x = n
var ok = truewhile (x > 0) {
val d = x % 10if (d ==0|| n % d !=0) { ok = false; break }
x /=10 }
if (ok) res.add(n)
}
return res
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defselfDividingNumbers(left, right):
res = []
for n in range(left, right+1):
x = n
ok =Truewhile x >0:
d = x %10if d ==0or n % d !=0:
ok =Falsebreak x //=10if ok:
res.append(n)
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
pubfnself_dividing_numbers(left: i32, right: i32) -> Vec<i32> {
letmut res = Vec::new();
for n in left..=right {
letmut x = n;
letmut ok =true;
while x >0 {
let d = x %10;
if d ==0|| n % d !=0 { ok =false; break; }
x /=10;
}
if ok { res.push(n); }
}
res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
functionselfDividingNumbers(left: number, right: number):number[] {
constres: number[] = [];
for (letn=left; n<=right; ++n) {
letx=n, ok=true;
while (x>0) {
constd=x%10;
if (d===0||n%d!==0) { ok=false; break; }
x= Math.floor(x/10);
}
if (ok) res.push(n);
}
returnres;
}