LeetCode 728. Self Dividing Numbers
阿新 • • 發佈:2018-02-17
true aries ole turn git ref ever self inpu
題目標簽:Math
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 = 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
.
題目標簽:Math
題目給了我們一個範圍,讓我們找到範圍裏面所有的 self-dividing number 加入 ArrayList 返回。 遍歷每一個數字,利用 % 10 拿到digit,檢查它是否是0,是否能被 數字整除;再利用 / 10 來去除掉這個digit。
Java Solution:
Runtime beats 42.86%
完成日期:02/16/2018
關鍵詞:Math
關鍵點:% 10 拿到digit;/ 10 去除digit
1 class Solution 2 { 3 public List<Integer> selfDividingNumbers(int left, int right) 4 { 5 List<Integer> res = new ArrayList<>(); 6 7 for(int i=left; i<=right; i++) //iterate each number 8 { 9 boolean sd = true; 10 int num = i; 11 12 while(num > 0) // check whether this number is self-dividing number 13 { 14 int digit = num % 10; 15 16 if(digit == 0 || i % digit != 0) 17 { 18 sd = false; 19 break; 20 } 21 22 num /= 10; 23 } 24 25 if(sd) 26 res.add(i); 27 } 28 29 return res; 30 } 31 }
參考資料:n/a
LeetCode 題目列表 - LeetCode Questions List
題目來源:https://leetcode.com/
LeetCode 728. Self Dividing Numbers