[Leetcode从零开刷]728. Self Dividing Numbers

来源:互联网 发布:知乎日报的rss 编辑:程序博客网 时间:2024/05/29 03:20

题目来源:
leetcode
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.

  • Example 1:
Input: left = 1, right = 22Output: [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.

翻译:
首先给出自分数的定义:给出一个数,他能被它的每个数字整除。
举例128是个自分数,因为128能被1整除,能被2整除,也能被8整除。
所以数字中不能出现0
所以题目是:给出一个下限和上限,返回其中所有自分数的列表。
上限和下限满足1<=left<=right<=10000

cpp:

class Solution {public:    vector<int> selfDividingNumbers(int left, int right) {           vector<int> v;        for (int i = left; i <= right; i++) {            int j= i;            for(;j>0;j /= 10){                int d= (j%10);                if (d == 0 || i % d != 0)break;  //每个值都要不是0 而且每个值都要能被除,要把所有数字都遍历完            }            if (j == 0) v.push_back(i);        }               return v;    }   };

对比带函数的cpp:

class Solution {public:    vector<int> selfDividingNumbers(int left, int right) {        vector<int> res;        for (int i = left; i <= right; i++) {            if (isSelfDividingNumbers(i))                res.push_back(i);        }        return res;    }    bool isSelfDividingNumbers(int num) {        int tmp = num, digit = 0;        for (; tmp >0 ;tmp /=10) {            digit = tmp % 10;            if (digit == 0 || num % digit != 0)                return false;  //不能break;        }        if(tmp == 0 )            return true;    }};
原创粉丝点击