2017-03-28 156 views
0

请尽可能简单的解释,因为我是一个初学者。 接收整数n并返回大于 n的最小整数,并且其中数位之和可被11整除。 例如,nextCRC(100)= 119,因为119是大于 100的第一个整数,而其数字1 + 1 + 9 = 11的总和可被11整除。需要帮助运行这个循环

1)我不明白的第一件事是,为什么在开始时for循环中存在“true”。

2)如何计算下一个数它是由11

3)如何为负数为此大于和整除,数字< 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)); 
} 
}