LeetCode | 728. Self Dividing Numbers

来源:互联网 发布:怎么搬家划算 知乎 编辑:程序博客网 时间:2024/05/19 23:11

A self-dividingnumber is a number that is divisibleby 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 containthe digit zero.

Given a lower and upper number bound, output a list ofevery possible self dividing number, including the bounds if possible.

Example 1:

Input:

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.

水题,问你输入一个范围,在这个范围里面的每一位都是这个数的约数的数有哪些,按照题目的意思去做就好了

但是这一题有一种更为简单的方法,就是to_string(int),将数字转换成string类型,然后一位一位取,这种方法比起我自己写的求每一位的方法要快,以后在取某个数字的每一位的时候,记得使用转换成string的方法

class Solution {

#define FOR(i,s,t) for(int i=s;i<=t;i++)

public:

   int inspect(int num)

    {

       int temp=num;

       int a,b;

       

       while(temp!=0)

       {

          a=temp%10;

           temp /=10;

           

           if(a==0) return false;

           if(num%a!=0) return false;

       }

       return true;

    }

   vector<int> selfDividingNumbers(int left, int right) {

       vector <int> nums;

       FOR(i,left,right)

       {

           if(inspect(i)) nums.push_back(i);

       }

        return nums;

       

    }

};

原创粉丝点击