62,628
社区成员
发帖
与我相关
我的任务
分享package math011;
public class Math011 {
public static void main(String[] args) {
int maxCycleLength=0;
for(int i=2; i<=1000; ++i) {
double tmpDecimal=(double)1/i;
String tmpStr=String.valueOf(tmpDecimal).substring(0,500);
int tmpCycleLength=getMaxCycleLength(tmpStr);
if(tmpCycleLength>maxCycleLength) {
maxCycleLength=tmpCycleLength;
}
}
System.out.println(maxCycleLength);
}
public static int getMaxCycleLength(String str) {
int maxCycleLength = 0;
int tmpCycleLength = 0;
for (int i = 1; i < str.length(); ++i) {
for (int j = 0; j < str.length() - i; ++j) {
if (str.charAt(j) == str.charAt(i + j))
tmpCycleLength++;
// As follow, tmpCycle is always change, and pass the value to the maxCycle,
// finally the value will be fixed.
else
tmpCycleLength = 0;
if (tmpCycleLength > maxCycleLength) {
maxCycleLength = tmpCycleLength;
}
}
}
if (maxCycleLength > 0)
return maxCycleLength;
return -1;
}
}
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
你把tmpDecimal转化为String类型,字符串没有500的长度,使用subString就报错了。