微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

728. Self Dividing Numbers

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 public class SelfDividingNumbers {
 5     /**
 6      * 728. Self Dividing Numbers
 7      * Easy
 8      * <p>
 9      * A self-dividing number is a number that is divisible by every digit it contains.
10      * For example,128 is a self-dividing number because 128 % 1 == 0,128 % 2 == 0,and 128 % 8 == 0.
11      * Also,a self-dividing number is not allowed to contain the digit zero.
12      * Given a lower and upper number bound,output a list of every possible self dividing number,including the bounds if possible.
13      * Example 1:
14      * Input:
15      * left = 1,right = 22
16      * Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]
17      * Note:
18      * The boundaries of each input argument are 1 <= left <= right <= 10000.
19      */
20     public List<Integer> solution(int left,int right) {
21         List<Integer> res = new ArrayList<>();
22         if (right < left)
23             return res;
24         for (int i = left; i <= right; i++) {
25             boolean flag = false;
26             int k = i;
27             while (!flag) {
28                 int km = k % 10;
29                 k = k / 10;
30                 if (km > 0 && i % km == 0 && k == 0) {
31                     flag = true;
32                     break;
33                 }
34                 if (km == 0 || i % km != 0)
35                     break;
36             }
37             if (flag)
38                 res.add(i);
39         }
40         return res;
41     }
42 
43     public List<Integer> solution2(int left,int right) {
44         List<Integer> list = new ArrayList<>();
45         for (int i = left; i <= right; i++) {
46             int j = i;
47             for (; j > 0; j /= 10) {
48                 if ((j % 10 == 0) || (i % (j % 10) != 0)) break;
49             }
50             if (j == 0) list.add(i);
51         }
52         return list;
53     }
54 
55     public static void main(String[] arg) {
56         SelfDividingNumbers s = new SelfDividingNumbers();
57         System.out.println(s.solution(1,22));
58     }
59 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐