Self Dividing Numbers
请访问最新更新版本:https://yanjia.me/zh/2018/11/…
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.
暴力法
复杂度
时间 O(NM)
思路
从左到右,对每个数字依次取出其各个位的数字,然后判断是否能整除。
代码
func selfDividingNumbers(left int, right int) []int {
var res []int
for ; left <= right; left++ {
curr := left
for curr > 0 {
rem := curr % 10
// the digit can't be zero and should be divisible
if rem == 0 || left%rem != 0 {
break
}
curr = curr / 10
}
if curr == 0 {
res = append(res, left)
}
}
return res
}