我认为如果您自己解决了这个问题,那么这对您可能会更好,但这是您的选择。 评论中的所有解释。
public static int countTriangle(List<Integer> list) {
if (list.size() == 0) {
// if list is empty return 0
return 0;
} else if (list.size() == 1) {
// if list contains only single element return this element
return list.get(0);
} else if (list.size() == 2) {
// if list contains two elements, return them connected
// for example we have list of 5 and 1
// we multiple 5 with 10 (50) and then add 1 to it,
// so the output of 5 and 1 will be 51
return list.get(0) * 10 + list.get(1);
}
// create new list for the next triangle's line
List<Integer> newList = new ArrayList<Integer>();
// iterate over every element of existing list
for (int i = 0; i < list.size() - 1; i++) {
// a = current element + next element (last iteration will be with last but one element)
int a = list.get(i) + list.get(i+1);
// if a has two digits or more
if (a >= 10) {
// translate it to String
String s = String.valueOf(a);
// take every char of a String, translate it to number and add to new list
// for example if a = 157 then three new elements will be added to new list (1, 5, 7)
for (int j = 0; j < s.length(); j++) {
newList.add(Integer.valueOf(String.valueOf(s.charAt(j))));
}
// if a has single digit
} else {
// add this to new list
newList.add(a);
}
}
// call this function with new list (next line)
return countTriangle(newList);
}
个人而言,我宁愿你首先表现出一些努力;你可以发布你有*不*工作?我也不清楚实际的计算规则是什么。 – 2014-10-08 12:00:53
@DaveNewton它就像一个向下的pascal三角形,除非你需要将两位数字分成两个一位数字,如果你有两个或一个数字留下这个方案,然后将两个数字合并成一个,你会得到一个数字 - 是我的猜测。 – EpicPandaForce 2014-10-08 12:03:35
这基本上只是列表操作,如果你可以有第二个'临时'列表,你计算出新的结果,然后替换原来的,那么它实际上非常容易 - 你只需添加'i'和'i + 1 ',添加到另一个列表中,检查数字是否大于10,将它们分成两个数字(首先除以10,然后将剩余部分作为新元素添加到该元素之后),然后检查是否有2个或更少列表中的元素,如果是,那么只需将其中的一个数字设置为5 * 10 + 1。这感觉就像是一个任务,我相信你可以做到这一点。 – EpicPandaForce 2014-10-08 12:07:16