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 <= 1000

 

题意:自我分裂数字的定义为:该数字可以被其自身每个数字所整除。
例:128是一个自我分裂数字,因为: 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0.
并且,一个自我分裂数字不允许包含数字0.
 给定一个较低的边界,一个较高的边界,输出该范围内的自我分裂数字,该范围包括边界。

方法一:直接根据题意要求进行判断。对当前数字i,判断i能否被其自身的每个数字整除。

public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> list = new ArrayList<>();
        for(int i = left; i <= right; i++){
            int temp = i;
            while(temp % 10 != 0){
                int n = temp % 10;
                if(i % n != 0)
                    break;
                temp /= 10;
            }
            if(temp == 0)
                list.add(i);
        }
        return list;
    }

LeetCode提供的答案:

利用字符与数字关系。将数字转换为字符串,再将字符串转换为字符数组,来判断每个数字

public List<Integer> selfDividingNumbers(int left, int right){
        List<Integer> list = new ArrayList<>();
        for(int i = left; i <= right; i++){
            if(isSelfDividing(i))
                list.add(i);
        }
        return list;
    }
    public boolean isSelfDividing(int n){
        for(char c : String.valueOf(n).toCharArray()){
            if(c == '0' || n % (c - '0') != 0)
                return false;
        }
        return true;
    }

 

posted @ 2018-01-10 20:24  zeroingToOne  阅读(218)  评论(0编辑  收藏  举报