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]
原文:https://leetcode.com/problems/self-dividing-numbers/description/
依題所示,如果一個(gè)數(shù)字可以整除它所有位上的數(shù)字,那么就稱(chēng)為self-dividing number,我們需要設(shè)計(jì)一個(gè)算法來(lái)求出指定范圍內(nèi)滿(mǎn)足的所有數(shù)字。
題目并不難,只需要不斷使用當(dāng)前數(shù)字除以不同位上的數(shù)字即可,但是需要注意的是self-dividing number中不含有0的,像10這種的肯定不行了,因?yàn)閚umber中一旦包含0就無(wú)法讓number本身除以0這一位了。
那么問(wèn)題就轉(zhuǎn)換成如果判斷數(shù)字中是否含0,對(duì)于像10、20、100、300 這種的可以直接讓其本身對(duì)10取模,觀察余數(shù)是否為0即可,像101、203這種的,讓其除以10,然后再取模運(yùn)算判斷。
那么很快便能寫(xiě)出如下解:
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
int temp = left;
vector<int> result;
for(int num=left;num<=right;num++) {// 在指定范圍內(nèi)循環(huán)
temp = num;
if(!(temp%10)) { // 判斷是否屬于10、20、300類(lèi)型
continue;
}
while(temp && num%(temp%10) == 0) {// 如果當(dāng)前位數(shù)滿(mǎn)足條件就繼續(xù)試探下一位
temp /= 10;
if(temp%10==0){ // 判斷是否屬于101、203這種的
break;
}
}
if(temp == 0) {
result.push_back(num);
}
}
return result;
}
};
這種是可以AC的,但是可以看到其中有不少冗余的代碼,那么就需要優(yōu)化一下減少冗余的代碼??梢钥闯銎渲衪emp%10的取模運(yùn)算重復(fù)了,那就可以使用一個(gè)mod變量直接保存。而100和101這種類(lèi)型的可以統(tǒng)一放在一起判斷。
代碼如下:
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
int temp = left;
int mod;
vector<int> result;
for(int num=left;num<=right;num++) {// 在指定范圍內(nèi)循環(huán)
temp = num;
while(temp) {
mod = temp%10; // 求出此時(shí)的余數(shù)
if(mod==0 || num%mod!=0)// 如果此時(shí)余數(shù)等于0說(shuō)明是10的倍數(shù)則退出,如果此時(shí)不滿(mǎn)足條件也退出
break;
temp /= 10;
}
if(temp == 0) {
result.push_back(num);
}
}
return result;
}
};