Self Dividing Numbers Problem


Description

LeetCode Problem 728.

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.

A self-dividing number is not allowed to contain the digit zero.

Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right].

Example 1:

1
2
Input: left = 1, right = 22
Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]

Example 2:

1
2
Input: left = 47, right = 85
Output: [48,55,66,77]

Constraints:

  • 1 <= left <= right <= 10^4


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    bool checkSelfDividing(int num) {
        bool isSelfDividing = true;
        int n = num, p;
        while (n > 0) {
            p = n % 10;
            if (p == 0) {
                isSelfDividing = false;
                break;
            }
            if (num % p != 0) {
                isSelfDividing = false;
                break;
            }
            n = n / 10;
        }
        return isSelfDividing;
    }
    
    vector<int> selfDividingNumbers(int left, int right) {
        vector<int> ans;
        for (int i = left; i <= right; i ++) {
            if (checkSelfDividing(i))
                ans.push_back(i);
        }
        return ans;
    }
};




Related Posts

Three Equal Parts Problem

LeetCode 927. You are given an array arr which consists...

Surface Area Of 3D Shapes Problem

LeetCode 892. You are given an n x n grid...

Super Palindromes Problem

LeetCode 906. Let’s say a positive integer is a super-palindrome...

Smallest Range I Problem

LeetCode 908. You are given an integer array nums and...

Projection Area Of 3D Shapes Problem

LeetCode 883. You are given an n x n grid...

Prime Palindrome Problem

LeetCode 866. Given an integer n, return the smallest prime...