【发布时间】:2017-06-04 04:33:29
【问题描述】:
我正在解决这个问题,(来自 Project Euler 的 41),我注意到 HashSet 的 contains 方法对于 Long 与 Integer 的工作方式不同(我可能在这里错了,如果我错了,请纠正我)。
问题是——
我们可以说一个 n 位数字是泛数字的,如果它使用 所有数字 1 到 n 恰好一次。例如,2143 是 4 位数字 pandigital,也是素数。
存在的最大 n 位泛数素数是多少?
我检查号码是否为 Pandigital 的代码是 -
private static boolean isPan(Long n) {
HashSet<Long> list = new HashSet<Long>();
int count = 0;
while(n != 0){
list.add(n%10);
count++;
n /= 10;
}
for(int i = 9; i>count; i--){
if(list.contains(i)) return false;
}
for(int i = 1; i<= count; i++){
if(!list.contains(i)) return false;
}
return true;
}
这段代码给了我一个无限循环。所以,我像这样更改了我的代码 -
private static boolean isPan(Long n) {
HashSet<Integer> list = new HashSet<Integer>();
int count = 0;
while(n != 0){
list.add((int) (n%10));
count++;
n /= 10;
}
for(int i = 9; i>count; i--){
if(list.contains(i)) return false;
}
for(int i = 1; i<= count; i++){
if(!list.contains(i)) return false;
}
return true;
}
我刚刚改了,HashSet<Long> 到 HashSet<Integer> 和 list.add(n%10) 到 list.add((int) n%10)。
这给了我正确的答案,7652413。那么,谁能解释为什么 Long 与 Integer 相比, contains 方法的工作方式不同?
【问题讨论】:
-
@pvg 我没有包含整个代码,因为只有这个方法返回错误。我不明白
this is almost certainly because your parameter doesn't actually fit in an int and is truncated,因为Long没有给我正确的答案,但Integer可以。 -
无论如何你都不能用 Set 做到这一点。您需要计算每个数字,而 Set 无法为您提供。当然,你根本不需要 Set,只需要一个由十个整数组成的数组。
-
@EJP 我使用 HashSet 来消除重复数字,因为我们需要一个不重复数字的 PanDigital 数字
-
我重复一遍。如果您使用 Set,您无法计算每个数字出现的次数。您不需要消除重复的数字:您需要计数它们。如果您将它们存储在 Set 中,那么在您计算它们之前,您已经丢失了重复项。你的算法没有意义。
-
@EJP 我不需要计算一个数字出现的次数,如果您看到我的代码,我正在使用 while 循环中的 count 变量计算数字的数量。 PanDigital 意味着它必须包含从 1 到 n 的所有数字,我在我的第二个 for 循环中检查它(当有任何数字重复时返回 false)。如果 number 包含大于 n 的数字(如 7654319)返回 false,我编写了第一个 for 循环。我就是这么写的。如果您想讲述其他内容,请详细说明。
标签: java long-integer hashset