2017-02-11 79 views
2

我编写了以下程序来计算可以被12整除但不包含数字重复的数字。例如。即使数字4出现的重复可以被12整除,也不会考虑数字144。问题是我没有输出。我尝试将循环范围从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"); 
    } 
} 

回答

0

在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"); 
} 
+1

非常感谢。这是一个愚蠢的错误,但让我发疯。感谢您的快速回复... – iamtejasva