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 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
.
解法1:
养成好习惯,一定要先写测试用例,然后写下伪代码,最后才是代码!切忌直接上代码!
ans = []
for num In range(left, right+1):
for each bit in num:
check num % bit == 0?
if all bit div is 0 then add num to ans
class Solution(object): def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] [1, 2, 3, 4, 5, 6, 7, 8, 9] [11, 12, 15] 10/1,2,5 [22=2*11, 24=2*2*2*3] 20/2,4, [33, 35, 36] 30/3,5,6 [44, 45, 48] 40/4,5,8 ... [99] [111, 112, 115] 110/? [122, 124] abcd = (a*1000+b*100+c*10+d)%a=0 (a*1000+b*100+c*10+d)%b=0 (a*1000+b*100+c*10+d)%c=0 (a*1000+b*100+c*10+d)%d=0 """ ans = [] for i in range(left, right+1): if self.is_div_num(i): ans.append(i) return ans def is_div_num(self, n): if n == 0: return False q = n while q: c = q % 10 if (c == 0) or (n % c != 0): return False q /= 10 return True
改进版本:
class Solution(object): def selfDividingNumbers(self, left, right): is_self_dividing = lambda num: '0' not in str(num) and all(num % int(digit) == 0 for digit in str(num)) return filter(is_self_dividing, range(left, right + 1))
关于all:
>>> all([1,2,3])
True
>>> all([1,2,0])
False
官方解法:
class Solution(object): def selfDividingNumbers(self, left, right): def self_dividing(n): for d in str(n): if d == '0' or n % int(d) > 0: return False return True """ Alternate implementation of self_dividing: def self_dividing(n): x = n while x > 0: x, d = divmod(x, 10) if d == 0 or n % d > 0: return False return True """ ans = [] for n in range(left, right + 1): if self_dividing(n): ans.append(n) return ans #Equals filter(self_dividing, range(left, right+1))
python2/3 one-liner:
[x for x in range(left, right+1) if all(y and not x%y for y in map(int,str(x)))]
>>> map(int, ["12","23"])
[12, 23]