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]
一个自我分裂的数字是一个数字,它可以被每个数字所包含。例如,128是自分割数,因为128 % 1 == 0
,128 % 2 == 0
和128 % 8 == 0
。而且,一个自分数的数字不允许包含数字零。给定一个较低和较高的数字边界,输出每个可能的自我分割数字的列表,如果可能的话,包括边界。
例1:
输入: 左= 1,右= 22 输出: [1,2,3,4,5,6,7,8,9,11,12,15,22]
(1)思想1:将每个数字num转换成字符串str,取出其每个位上的数str[i],进行判断。如果该位置上的数str[i]=0, 则返回false;如果num % str[i] != 0,则返回false;否则返回true。
C++代码:
1 class Solution { 2 public: 3 vector<int> selfDividingNumbers(int left, int right) { 4 vector<int> v; 5 for(int i=left;i<=right;i++) 6 { 7 if(is_valid(i)) 8 v.push_back(i); 9 } 10 return v; 11 } 12 bool is_valid(int num) 13 { 14 string str=to_string(num); 15 for(int i=0;i<str.size();i++) 16 { 17 char c=str[i]; 18 if(c=='0') 19 return false; 20 if(num%(c-'0')!=0) 21 return false; 22 } 23 return true; 24 } 25 };
python代码:
1 class Solution: 2 def selfDividingNumbers(self, left, right): 3 L=[] 4 for x in range(left,right+1): 5 str='%d' %x 6 for c in str: 7 if c=='0': 8 flag=0 9 break 10 elif x%(int(c))!=0: 11 flag=0 12 break 13 else: 14 flag=1 15 if flag: 16 L.append(x) 17 return L