742. 数字整除数
一个数字整除数是指一个可以被其中包含的每个数字整除的数.
举个例子, 128是一个数字整除数, 因为 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
并且, 数字整除数不允许包含数字 0.
给出数字取值的上下限, 输出一个包含所有数字整除数的列表, 包括边界.
注意事项
0<=L<=R<=2^31-1,R-L<=10^6
样例
给出 left = 1
, right = 22
, 返回 [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
本身并不难的一个题,但在一个case上卡了好久,发现了一个很有意思的问题。这道题的通过率只有12%,估计都和我一样卡在这个case上了。
问题在于当int类型的index做下标进行循环时会在2147483647时继续index++,然后再与2147483647进行比较,但这时index已经溢出成为-2147483648,因此表达式仍成立,会继续进行循环。
auto f = [&](int& a, int b) {
cout << "if " << a << "<=" << b << endl;
return a <= b;
};
auto f1 = [&](int& a) {
a++;
cout << "lower++:" << a << endl;
};
for (int lower= 2147483646; f(lower,2147483647); f1(lower)) {
system("pause");
}
system("pause");
结果如下所示
而这道题默认传入的lower是int类型,拿来直接用结果就gg了,需要换成__int64类型,或者做一下特殊处理。
class Solution {
public:
/**
* @param lower: Integer : lower bound
* @param upper: Integer : upper bound
* @return: a list of every possible Digit Divide Numbers
*/
vector<int> digitDivideNums(long long lower, int upper) {
// write your code here
vector<int> result;
for(;lower<=upper;lower++)
{
int d = lower;
long long c = 1;
int x;
while (d/c!=0 ) {
x = (d / c) % 10;
if (x == 0 || lower % x != 0) break;
c *= 10;
}
if (d / c != 0) continue;
result.push_back(lower);
}
return result;
}
};