LeetCode 728. Self Dividing Numbers

Posted 几米空间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 728. Self Dividing Numbers相关的知识,希望对你有一定的参考价值。

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 == 0128 % 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.

 


题目标签:Math

 

  题目给了我们一个范围,让我们找到范围里面所有的 self-dividing number 加入 ArrayList 返回。
 
  遍历每一个数字,利用 % 10 拿到digit,检查它是否是0,是否能被 数字整除;再利用 / 10 来去除掉这个digit。
  
 
 
 

Java Solution:

Runtime beats 42.86% 

完成日期:02/16/2018

关键词:Math

关键点:% 10 拿到digit;/ 10 去除digit

 1 class Solution 
 2 {
 3     public List<Integer> selfDividingNumbers(int left, int right) 
 4     {
 5         List<Integer> res = new ArrayList<>();
 6         
 7         for(int i=left; i<=right; i++) // iterate each number
 8         {
 9             boolean sd = true;
10             int num = i;
11             
12             while(num > 0) // check whether this number is self-dividing number
13             {
14                 int digit = num % 10;
15                 
16                 if(digit == 0 || i % digit != 0)
17                 {
18                     sd = false;
19                     break;
20                 }
21                 
22                 num /= 10;
23             }
24             
25             if(sd)
26                 res.add(i);
27         }
28         
29         return res;
30     }
31 }

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

以上是关于LeetCode 728. Self Dividing Numbers的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 728. Self Dividing Numbers

Leetcode #728. Self Dividing Numbers

Python 解leetcode:728. Self Dividing Numbers

leetcode-728-Self Dividing Numbers

[LeetCode] 728. Self Dividing Numbers

算法--leetcode 728. Self Dividing Numbers