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:

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.


class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {

        List<Integer> result = new ArrayList<>();
//iterate through each number within the rnge of left and right (inclusive)
//provided as input.
        for(int i=left; i<=right; i++){
// if the number is not divisible by 10 and it is divisible by every digit it
// contains then add the number in the list of self dividing numbers.
        if(i%10 != 0 && selfDividing(i)){


// return the final list of self dividing numbers.        
         return result;
//method selfDividing which has the input number that is to be verified whether
// it is self dividing or not.     
        public boolean selfDividing(int i){
// initialize the num integer with the input number.          
            int num =i;
            int digit;
// while the value of integer num is greater than 0 do the following:            
            while(num > 0){
// initialize digit with the remainder resulting from the division of integer
// num by 10.This remainder will be the last digit of the integer num.              
// if the digit is equal to 0 or it gives a remainder greater than 0 upon
// division by the inout number then the number is not a self dividing number,
// return false.
                if(digit == 0 || (i%digit)>0 ){
                    return false;
// else initialize integer num by dividing the integer num itself by 10. This
//will give the remaining digits of the number that needs to be checked for
//division by input number.                
// if the while loop succeeds without any return as false in between then the
// input number is a self dividing number, hence return true.             
            return true;


Test Cases

  1. Input left and right =0.
  2. Input the number range in which the boundary values are self dividing. for eg. left =1 and right= 22.
  3. Input the range which has numbers having 0 at the beginning, in between and at the end. for eg. left=010 and right=101.
  4. Input the maximum range possible. for eg. left= 1 and right= 10,000.
  5. Input a range where left=right and are self dividing numbers. for eg. left = 99 and right= 99.
  6. Input a range where left is greater than right, for eg. left= 99 and right= 1.
  7. Input a negative number in the range. The output of this condition depends on the requirement. for eg. left = -100 and right= 100 (negative testing).

See also