problem
solution1: 使用string类型来表示每位上的数字;
class Solution { public: vector<int> selfDividingNumbers(int left, int right) { vector<int> res; for (int i=left; i<=right; ++i) { bool flag = isSDN(i); if(flag) res.push_back(i); } return res; } bool isSDN(int num) { string str = to_string(num); for(auto ch : str) { if(ch=='0' || num%(ch-'0')!=0) return false; } return true; } };
solution2: 使用数学计算来check每一个数字;
问题1:求解余数的语句;
问题2:需要先求解一次余数,再计算除数,即下一次计算需要用到的被除数。
class Solution { public: vector<int> selfDividingNumbers(int left, int right) { vector<int> res; for (int i=left; i<=right; ++i) { bool flag = isSDN(i); if(flag) res.push_back(i); } return res; } bool isSDN(int num) { int tmp = num; int reminder = 0; while(tmp) { reminder = tmp%10;//err.. tmp /= 10;//err.. if(reminder == 0 || ((num%reminder) != 0)) return false; } if(tmp==0) return true; else return false; } };
参考
1. Leetcode_easy_728. Self Dividing Numbers;
2. Grandyang;
完