因为我是初学者,请尽可能简单地解释。 接收整数n并返回大于的最小整数 n,其中数字之和可被11整除。 例如,nextCRC(100)= 119,因为119是第一个大于的整数 100及其数字1 + 1 + 9 = 11的总和可被11整除。
1)我无法理解的第一件事是,为什么在开始时for循环中存在“true”。
2)如何计算大于11且可被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 :(得分: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));
}
}