A self-dividing number is a number that is divisible by every digit it contains.
Explanation:
128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Example 1:
Input: left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
Approach
Java
import java.util.ArrayList;import java.util.List;public class SelfDividingNumbers {public static void main(String[] args) {int start = 1;int end = 22;List<Integer> sdN = selfDividingNumbers(start, end);System.out.println(sdN);}// Method to find selft dividing numberpublic static List<Integer> selfDividingNumbers(int left, int right) {List<Integer> list = new ArrayList<>();// iterate from to till endfor (int i = left; i <= right; i++) {// is true then add into resultif (isSelfDividing(i))list.add(i);}return list;}// check number isSelfDividingprivate static boolean isSelfDividing(int n) {// till 9 all are self dividingif (n < 9)return true;int tmp = n;// iterate till 0while (tmp != 0) {int mode = tmp % 10;// if mode 0 thenif (mode == 0)return false;// if not then falseif (n % mode != 0)return false;tmp /= 10;}return true;}}
C++
#include <bits/stdc++.h>using namespace std;// check number isSelfDividingbool isSelfDividing(int n){// till 9 all are self dividingif (n < 9)return true;int tmp = n;// iterate till 0while (tmp != 0) {int mode = tmp % 10;// if mode 0 thenif (mode == 0)return false;// if not then falseif (n % mode != 0)return false;tmp /= 10;}return true;}//function to find selft dividing numbervector<int> selfDividingNumbers(int left, int right){vector<int> list;// iterate from to till endfor (int i = left; i <= right; i++) {// is true then add into resultif (isSelfDividing(i))list.push_back(i);}return list;}int main(){int start = 1;int end = 22;vector<int> sdN= selfDividingNumbers(start, end);for(int i=0;i<sdN.size();i++)cout<<sdN[i]<<" ";}
No comments:
Post a Comment