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 nu
https://leetcode-cn.com/problems/self-dividing-numbers/description/
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 1:
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.
思路,遍历数组,对每一个数,从低位到高位判断,用模运算%和int除法
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> result;
for(int i = left; i <= right; i++) {
int j = i;
while(j != 0) {
if ((j % 10 == 0) || (i % (j%10) != 0)) break;
j = j/10;
}
if(j == 0) result.push_back(i);
}
return result;
}
};
py
class Solution:
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
res = []
for i in range(left, right+1):
k = i #用k来每次取最低位
while k > 0:
j = k % 10
if j == 0 or i % j != 0:
break
k = k // 10
if k == 0: #全部符合,找到
res.append(i)
return res
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)