[leetcode]728. Self Dividing Numbers
Analysis
ummmm~—— [ummmm~]
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
简单题~
Implement
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> res;
for(int i=left; i<=right; i++){
int tmp = i;
bool flag = true;
while(tmp){
int t = tmp%10;
if(t == 0 || i%t != 0){
flag = false;
break;
}
tmp /= 10;
}
if(flag)
res.push_back(i);
}
return res;
}
};
本来想着直接把1-10000中所有的数都判断好,然后再返回left和right之间的满足条件的数,发现效率比较低!!
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
int isSelf[10001] = {0};
for(int i=1; i<=10000; i++){
int tmp = i;
bool flag = true;
while(tmp){
int t = tmp%10;
if(t == 0 || i%t != 0){
flag = false;
break;
}
tmp /= 10;
}
if(flag)
isSelf[i] = 1;
}
vector<int> res;
for(int i=left; i<=right; i++){
if(isSelf[i] == 1)
res.push_back(i);
}
return res;
}
};