您的位置:首页 > 其它

LeetCode-728. Self Dividing Numbers

2018-01-26 13:39 309 查看

Description



Example 1



Note



Solution 1(C++)

class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> res;
for(int i=left;i <= right;i++){
if(isDividingNumbers(i)){
res.push_back(i);
}
}
return res;
}
bool isDividingNumbers(int &num){
vector<int> digits;
int temp = num;
while(temp != 0){
int i=temp % 10;
digits.push_back(i);
temp=temp / 10;
}
for(auto n:digits){
if(n !=0 && num%n == 0){ continue; }
else { return false; }
}
return true;
}
};


Solution 2(C++)

class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> res;
int temp,j;
for(int i=left;i <= right;i++){
temp=i;
while(temp != 0){
j=temp % 10;
if(j == 0 || i % j != 0) break;
temp /= 10;
}
if(temp == 0) res.push_back(i);
else continue;
}
return res;
}
};


算法分析

解法一与解法二并没有本质的区别,只是更改了一下程序的写法,不过这样更改之后,解法二确实比解法一缩短了一定的运算时间。

程序分析

解法一与解法二的主要区别就是程序编写上的区别。这个就不啰嗦了。此外,可以复习一下获取整数的各个位数:

while(temp != 0){
int i=temp % 10;
digits.push_back(i);
temp=temp / 10;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: