-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
61 lines (54 loc) · 1.59 KB
/
main.cpp
File metadata and controls
61 lines (54 loc) · 1.59 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Source: https://leetcode.com/problems/self-dividing-numbers
// Title: Self Dividing Numbers
// Difficulty: Easy
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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]` (both **inclusive**).
//
// **Example 1:**
//
// ```
// Input: left = 1, right = 22
// Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]
// ```
//
// **Example 2:**
//
// ```
// Input: left = 47, right = 85
// Output: [48,55,66,77]
// ```
//
// **Constraints:**
//
// - `1 <= left <= right <= 10^4`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <vector>
using namespace std;
class Solution {
static bool selfDivisible(int n) {
int tmp = n;
while (tmp > 0) {
int digit = tmp % 10;
if (digit == 0 || n % digit != 0) return false;
tmp /= 10;
}
return true;
}
public:
vector<int> selfDividingNumbers(int left, int right) {
auto ans = vector<int>();
ans.reserve(right - left + 1);
for (int num = left; num <= right; ++num) {
if (selfDivisible(num)) ans.push_back(num);
}
return ans;
}
};