從1開始,求出全部的和爲21的連續正整數數列。好比1+2+3+4+5+6 和爲 21, 6+7+8和爲21。
python
解法:該題目仍然須要首尾兩個指針,一個爲start,一個爲end。sum=start+end。 若是sum大於21,start後移,若是等於21,打印start到end的數列。start,end所有後移。若是小於21,end後移。指針移動時。注意,sum的值也要相應變化。
ide
def addSeq(n): start, end = 1, 2 stop = (n+1) / 2 mysum = start + end while start < stop: if mysum == n: print range(start, end+1) mysum -= start start += 1 end += 1 mysum += end elif mysum < n: end += 1 mysum += end else: mysum -= start start += 1 if __name__ == '__main__': addSeq(21)
答案:指針
C:\Python27\python.exe E:/cyou-inc.com/test/test.pyit
[1, 2, 3, 4, 5, 6]class
[6, 7, 8]test
[10, 11]top