題目描述
小明很喜歡數學,有一天他在做數學作業時,要求計算出9~16的和,他馬上就寫出了正確答案是100。但是他並不滿足於此,他在想究竟有多少種連續的正數序列的和爲100(至少包括兩個數)。沒多久,他就得到另一組連續正數和爲100的序列:18,19,20,21,22。現在把問題交給你,你能不能也很快的找出所有和爲S的連續正數序列? Good Luck!
輸出描述:
輸出所有和爲S的連續正數序列。序列內按照從小至大的順序,序列間按照開始數字從小到大的順序
解析思路
運行代碼
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
int plow = 1;
int phigh = 2;
while(phigh > plow){
int cur = ((plow + phigh)*(phigh - plow + 1)) >> 1;
if(cur == sum){
ArrayList<Integer> list = new ArrayList<>();
for(int i = plow;i <= phigh;i++){
list.add(i);
}
result.add(list);
plow++; //此句很重要,不加則無法跳出while
}
if(cur < sum){
phigh++;
}
if(cur > sum){
plow++;
}
}
return result;
}
}