LeetCode 728. Self Dividing Numbers

来源:互联网 发布:idea打印不出sql 编辑:程序博客网 时间:2024/05/19 23:58
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.若取余得到的一位数为0则判断终止(0不可以作为被除数,即不符合条件),
               2.用取余得到的一位数对整数数字进行取余 结果不为0(说明不能被整除,不符合条件),跳出循环;

代码实现如下:
第一版:
class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> res = new ArrayList<>();
        for(int n = left; n <= right; n++){
           if(selfDividing(n)) res.add(n);
        }
        return res;
    }

    public boolean selfDividing(int n){
         int x = n ;
         while(x > 0){
            int d = x % 10;
            x = x / 10;
            if(d == 0 || (n % d != 0)) return false;
         }
        return true;
    }
}

第二版:
class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> ans = new ArrayList();
        for (int n = left; n <= right; ++n) {
            if (selfDividing(n)) ans.add(n);
        }
        return ans;
    }
    
    public boolean selfDividing(int n) {
        for (char c: String.valueOf(n).toCharArray()) {
            if (c == '0' || (n % (c - '0') != 0))
                return false;
        }
        return true;
    }
}
原创粉丝点击