1. 程式人生 > >159、自除數

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;
    }
}