728. Self Dividing Numbers

原题链接:https://leetcode.com/problems/self-dividing-numbers/description/
看到这道题目,我想到的最直接最简单的方法:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.int2Array(35));
        System.out.println(s.selfDividingNumbers(1, 22));
    }

    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> res = new ArrayList<>();
        for (int i = left; i <= right; i++) {
            boolean isDividingNumber = true;
            for (Integer temp : int2Array(i)) {
                if (temp == 0 || i % temp != 0) {
                    isDividingNumber = false;
                    break;
                }
            }
            if (isDividingNumber) {
                res.add(i);
            }
        }
        return res;
    }

    private Set<Integer> int2Array(int item) {
        Set<Integer> res = new HashSet<>();
        while (item >= 10) {
            res.add(item % 10);
            item = item / 10;
        }
        res.add(item);
        return res;
    }
}

虽然是通过了,但是时间复杂度和空间复杂度稍微高一点。看一下官方给出的暴力的答案吧,虽然时间复杂度和空间复杂度和我的差不多,但是代码要简洁点:

import java.util.ArrayList;
import java.util.List;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.selfDividingNumbers(1, 22));
    }

    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> res = new ArrayList<>();
        for (int i = left; i <= right; i++) {
            if (check(i)) {
                res.add(i);
            }
        }
        return res;
    }

    private boolean check(int item) {
        for (char c : String.valueOf(item).toCharArray()) {
            if (c == '0' || item % (c - '0') > 0) {
                return false;
            }
        }
        return true;
    }
}
posted @ 2018-03-17 11:27  optor  阅读(136)  评论(0编辑  收藏  举报