自除数
题目
题目分析
1.这道题可以直接用暴力求解,动用for循环遍历从left到right的每个数,使用while判断是否为自除数。
2.满足自除数有两个要求:1.数位不能存在0;2.自除数除于数位为0;这里可以使用if语句进行判断。
3.由于自除数的数量位置,所以存储自除数可以采用容器或者数列来存储。
代码
#include<iostream> #include<vector> using namespace std; vector<int> selfDividingNumbers(int left, int right) { vector<int>show; for (int i = left; i <= right; i++) { int temp = i; bool estimate = true; while (temp != 0) { int t = temp % 10; if (t == 0 || i % t != 0) { estimate = false; break; } temp /= 10; } if (estimate) { show.push_back(i); } } return show; } int main() { int left, right; cin >> left >> right; vector<int> result = selfDividingNumbers(left, right); for (int num : result) { cout << num << " "; } return 0; }
下面是通过力扣测试的代码
class Solution { public: vector<int> selfDividingNumbers(int left, int right) { vector<int>show; for (int i = left; i <= right; i++) { int temp = i; bool estimate = true; while (temp != 0) { int t = temp % 10; if (t == 0 || i % t != 0) { estimate = false; break; } temp /= 10; } if (estimate) { show.push_back(i); } } return show; } };
标签:selfDividingNumbers,right,int,c++,力扣,vector,例题,除数,left From: https://www.cnblogs.com/hcrzhi/p/18092585