728. Self Dividing Numbers
Easy
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:
1 | Input: |
Note:
The boundaries of each input argument are 1 <= left <= right <= 10000
.
题目解释:判断一个数是否是自除数,即数字对各个位的上数取余等于0;
方案一
思路:遍历所有数,并遍历每个数的每个位进行取余操作;
1 | class Solution { |
result:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Self Dividing Numbers.
Memory Usage: 8.5 MB, less than 30.71% of C++ online submissions for Self Dividing Numbers.
方案二
数字用string转换,再遍历
1 | class Solution { |
result
Runtime: 8 ms, faster than 30.71% of C++ online submissions for Self Dividing Numbers.
Memory Usage: 8.6 MB, less than 21.41% of C++ online submissions for Self Dividing Numbers.
虽然可行,但是效率还是差了点;
讨论区还有对应的使用固定大小数组进行判断的方案,在空间占用上会相对优势些:
Correct C++ Solution(Numbers up to 9999) Better than 100% in runtime and 95% in storage-Better-than-100-in-runtime-and-95-in-storage>)
执行结果如下:
Runtime: 4 ms, faster than 86.79% of C++ online submissions for Self Dividing Numbers.
Memory Usage: 8.4 MB, less than 67.63% of C++ online submissions for Self Dividing Numbers.