检查一系列数字的可分割性,不重复数字

  • 本文关键字:数字 可分割 一系列 java
  • 更新时间 :
  • 英文 :


我编写了以下程序来计算可被12整除但不包含重复数字的数字。例如,即使数字144可被12整除,也不考虑数字144,因为存在数字4的重复。问题是我没有输出。我试着将for循环的范围从12…54321更改为12…1000,甚至12…24。我仍然没有输出。我似乎找不到问题出在哪里。有人能告诉我我的代码出了什么问题吗。或者只是向我建议一个更好的代码/问题解决方案。谢谢

class mod12
{
public static void main(String[] args)
{
int count=0;
for(int num=12;num<=54321;num+=12)
{
boolean repetition=false;
int digits[]=new int[10];
int length=0;
while (num!=0)
{
digits[length++]=num%10;
num=num/10;
}
for(int i=0; i<length; i++)
{
for(int j=0; j<length; j++)
{
if(i!=j)
{
if(digits[i]==digits[j])
{
repetition=true;
break;
}
}
}
}
if(repetition==false)
{count++;}
}
System.out.println("There are "+count+" numbers satisfying the condition");
}
}

在while循环中,您减少了num,有效地向后移动了for循环,因此它永远不会完成。使用临时变量可以解决问题:

public static void main(String[] args)
{
int count=0;
for(int num=12;num<=54321;num+=12)
{
boolean repetition=false;
int digits[]=new int[10];
int length=0;
int tempNum = num; // Here
while (tempNum !=0)
{
digits[length++]=tempNum %10;
tempNum =tempNum /10;
}
for(int i=0; i<length; i++)
{
for(int j=0; j<length; j++)
{
if(i!=j)
{
if(digits[i]==digits[j])
{
repetition=true;
break;
}
}
}
}
if(repetition==false)
{count++;}
}
System.out.println("There are "+count+" numbers satisfying the condition");
}

编辑:
不管最初的问题是什么,请注意,使用Set跟踪数字可以大大缩短代码:

public static void main(String[] args) {
int count = 0;
NUMBERS:
for (int num = 12; num <= 54321; num += 12) {
Set<Integer> digits = new HashSet<>();
int tempNum = num;
while (tempNum != 0) {
int digit = tempNum % 10;
if (!digits.add(digit)) {
continue NUMBERS;
}
tempNum = tempNum / 10;
}
++count;
}
System.out.println("There are "+count+" numbers satisfying the condition");
}

最新更新