我認爲如果您自己解決了這個問題,那麼這對您可能會更好,但這是您的選擇。 評論中的所有解釋。
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