159、自除数

自除数 是指可以被它包含的每一位数除尽的数。

例如,128 是一个自除数,因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。

还有,自除数不允许包含 0 。

给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。

示例 1:

输入:
上边界left = 1, 下边界right = 22
输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
注意:

每个输入参数的边界满足 1 <= left <= right <= 10000。
没有技术含量的,但是肯定有更好的解法

class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> result = new ArrayList<>();
		for (int i = left; i <= right; i++) {
			int j = i;
			while (j!=0) {
				int tem = j % 10;
				j = j/10;
				if(  tem == 0||i % tem != 0 ){
					break;
				}
				if( j == 0 ){
					result.add(i);
				}	
			}	
		}	
		return result;
    }
}

好吧,好像没什么技巧
排名靠前的代码也是这么做的

class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> res = new ArrayList<Integer>();
        int num = left;
        while (num <= right){
            if (isSelfDivNum(num))
                res.add(num);
            num ++;
        }
        return res;
    }
    public boolean isSelfDivNum(int num){
        int digit;
        int tmp = num;
        while(tmp!= 0){
           digit = tmp % 10;
            if(digit ==0 || num % digit != 0)
                return false;
            tmp = tmp / 10;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/85793351
今日推荐