【发布时间】:2015-11-22 03:34:28
【问题描述】:
如果该数字具有以下属性,则为数字“聚合数字”: 就像斐波那契数列 1,1,2,3,5,8,13.....
数字中的数字可以分为几个部分,后面部分是前面部分的总和。
喜欢
112358, because 1+1=2, 1+2=3, 2+3=5, 3+5=8
122436 because 12+24=36
1299111210, because 12+99=111, 99+111=210
112112224, because 112+112=224
需要提供一个函数来检查这个数字是否是聚合数字?
我写了代码,但需要优化它。请帮忙
public class AggragetedNumber {
public static void main(String[] args) {
System.out.println(isAggregatedNumber("1121325"));
}
static boolean isAggregatedNumber(String text) {
int length = text.length() / 2;
for (int i = 1; i <= length; i++) {
for (int j = 2; j <= length; j++) {
if (Match(i, j, text)) {
return true;
}
}
}
return false;
}
static boolean Match(int i, int j, String text) {
String first = text.substring(0, i);
String second = text.substring(i, i * 2);
StringBuilder buffer = new StringBuilder(first);
buffer.append(second);
while (buffer.length() < text.length()) {
Integer x = (Integer.parseInt(first) + Integer.parseInt(second));
String third = x.toString();
buffer.append(third);
first = second;
second = third;
}
if (text.equals(buffer.toString()))
return true;
return false;
}
}
【问题讨论】:
-
111121325 - 11 + 1 = 12 怎么样; 1 + 12 = 13; 12 + 13 = 25,但你的程序返回 false
-
感谢@BOND3,我刚刚测试了 3-4 个案例,有任何改进建议。
标签: java algorithm optimization