連續的正數序列,使得和為指定值

來源:互聯網
上載者:User

題目:

連續的正數序列,使得和為指定值

分析:

以前做過類似的題目,求解兩個數字和為指定值這種題目,採用先排序,然後從兩頭開始尋找的方式,這題其實也差不多,採用兩個指標,不過這次兩個指標同時從頭開始尋找,初始化時first指標指向1,second指標指向2,如果curr_sum小於指定的sum,second指標往後移東;相反,如果curr_sum大於指定的sum,first指標往後移動。

代碼如下:

#include <iostream>#include <cstdlib>#include <cstdio>using namespace std;//輸出序列void printSequence(int small, int big){if(small > big)return ;for(int i = small; i <= big; i++)cout << i << " ";cout << endl;return ;}int main(){int sum = 10001;int small = 1;int big = 2;int middle = (1 + sum) / 2;int curr_sum = small + big;while(small < middle){if(curr_sum == sum)printSequence(small, big);else{while(curr_sum > sum && small < middle)//一直迴圈,知道當前的和比sum小{curr_sum = curr_sum - small;small++;if(curr_sum == sum)printSequence(small, big);}}big++;curr_sum += big;}return 0;}

總結:

學會用指標,尤其多個指標,可以解決很多有意思的問題。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.