[Math_Easy]728.Self Dividing Numbers

原题:728.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

examples

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

题目大意

一个self_deviding数能够被它所包含的所有数字整除。现在给出一组数的上界和下界,求出所有是self_dividing number的数,因为0不能作为除数,所以肯定不能有数字0

解题思路

将每个数字依次分解保留在一个数组中,再遍历数组把每个元素当作除数进行取余

代码

class Solution {
public:
    vector<int> selfDividingNumbers(int left, int right) 
    {
        vector<int> ans;
        int i=0,j=0;
        for(i=left;i<=right;i++)
        {
            int a[5]={0};
            int temp=i,k=0;
            while(temp)
            {
                a[k++]=temp%10;
                temp/=10;
            }
            for(j=0;j<k;j++)
            {
                if(a[j]==0||(i%a[j])!=0)
                    break;
            }
            if(j==k)
                ans.push_back(i);
        }
        return ans;
    }
};
posted @ 2018-08-21 21:31  默写年华  阅读(130)  评论(0编辑  收藏  举报