2017-02-11 4 views
2

12で割り切れるが数字の繰り返しを含まない数字を数えるために、次のプログラムを書いた。例えば。数字4の繰り返しが存在するために12で割り切れるにもかかわらず、数字144は考慮されない。問題は、出力が得られないことです。私はforループの範囲を12 ... 54321から12 ... 1000、さらには12 ... 24に変更しようとしました。私はまだ出力がありません。私は問題が何かを見つけることができない。誰かが私のコードで何が間違っているか教えてください。あるいは、私は問題のより良いコード/解決策を提案するだけです。おかげで... whileループで数字の繰り返しのない数値の範囲のチェック

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

あなたは効果的に後方forループを移動し、numを減らし、それが完了したことがありません。代わりに、一時的な変数を使用することで、問題を解決するだろう:

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

EDIT:
かかわらず、元の質問の、あなたは数字を追跡するために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