2017-03-28 14 views
0

私は初心者のため、できるだけ簡単に説明してください。 整数nを受け取り、 nより大きい最小の整数を返します。数字の合計は11で割り切れます。 たとえば、119が最初に より大きい整数であるため、nextCRC(100)= 119となります。 1 + 1 + 9 = 11の桁の合計は11で割り切れる。ループでこれを実行する際に助けが必要

1)私が理解できない最初のことは、開始時にforループに "true"がある理由です。私は負の数のためにこれを行うにはどうすればよい11

3)によってより大きいと割り切れる次の数を計算するにはどうすればよい

2)、数字< 0。

public static int nextCRC(int n) 
{ 
    try 
    { 
     **for (int i = n + 1; true; i++)** 
     { 
      String number = String.valueOf(Math.abs(i)); 

      int count = 0; 
      for (int j = 0; j < number.length(); j++) 
      { 
       count += Integer.parseInt(String.valueOf(number.charAt(j))); 
      } 

      if (count > 0 && count % 11 == 0) return i; 
     } 
    } 
    catch (Exception e) 
    { 
     return 0; 
    } 
} 

public static void main(String[] args) 
{ 
    System.out.println(nextCRC(100)); 
    System.out.println(nextCRC(-100)); 
} 

}

+0

1) 'true'には、単に "壊れることはありません" という意味。各ループ反復の前にセミコロン間の式が評価され、偽であればループが壊れ、ループの後に来るものに実行が移ります。実際には不要です:for(int i = n + 1; i ++)は同じことをします。 –

+0

2)文字列に変換する必要はありません。あなたがこれをよりうまくやる方法を示すSO(および他の場所)に関する多くの質問があります。 –

答えて

0

私は、コードの各部分が何をするかを説明するコードにコメントを追加しました:

public static int nextCRC(int n) 
{ 
try 
{ 
    for (int i = n + 1; true; i++) // the for loop will loop as long as the boolean is true. i starts at the inputted value and increments by 1 each iteration 
//Since the value is "true" it will loop forever or until a value is returned 
    { 
     String number = String.valueOf(Math.abs(i)); // convert the number to string 

     int count = 0; 
     for (int j = 0; j < number.length(); j++) //iterate through each digit in the number 
     { 
      count += Integer.parseInt(String.valueOf(number.charAt(j))); // add the value of each digit to cout variable 
     } 

     if (count > 0 && count % 11 == 0) return i; //return the number that was checked if the sum of its digits is divisible by 11 
    } 
} 
catch (Exception e) // return a value of 0 if there is an exception 
{ 
    return 0; 
} 
} 

public static void main(String[] args) 
{ 
System.out.println(nextCRC(100)); 
System.out.println(nextCRC(-100)); 
} 
} 
関連する問題