[LeetCode] 728.Self Dividing Numbers
- 题目描述
- 解题思路
- 实验代码
题目描述
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.
Example:
Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
Note:
The boundaries of each input argument are 1 <= left <= right <= 10000
.
解题思路
这道题目就是要找到所给边界之内的自分数self-dividing number,首先明确self-dividing number的概念,就是它可以被自己的每一位数整除。那么先想特殊情况,如果位数中有0,则它不可能是self-dividing number,因为除数不能为0。想到这一点之后其实没什么难点了,我的做法是想将该数转为字符串然后将每一位提出来转为int值,再用原来的数除以这个位数,如果最后成功整除次数等于原来数的位数则原来的数就是所要的self-dividing number。
实验代码
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> v;
for (int i = left; i <= right; i++) {
stringstream ss;
ss << i;
string s = ss.str();
int l = s.length(), t = 0;
for (int j = 0; j < l; j++) {
if (s[j] == '0') break;
if (i % (s[j]-'0') == 0)
t++;
}
if (l == t) v.push_back(i);
}
return v;
}
};