JZ-C-41-Plus

剑指offer第四十一题-拓展:和为s的连续正数序列:输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)

 1 //============================================================================
 2 // Name        : JZ-C-41-Plus.cpp
 3 // Author      : Laughing_Lz
 4 // Version     :
 5 // Copyright   : All Right Reserved
 6 // Description : 和为s的连续正数序列:输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)
 7 //============================================================================
 8 
 9 #include <iostream>
10 #include <stdio.h>
11 using namespace std;
12 
13 void PrintContinuousSequence(int small, int big);
14 
15 void FindContinuousSequence(int sum) {
16     if (sum < 3)
17         return;
18 
19     int small = 1;
20     int big = 2;
21     int middle = (1 + sum) / 2;
22     int curSum = small + big; //这里curSum其实是从small到big之间所有数字的累加和
23 
24     while (small < middle) {
25         if (curSum == sum)
26             PrintContinuousSequence(small, big);
27 
28         while (curSum > sum && small < middle) {
29             curSum -= small; //每次更新curSum值
30             small++;
31 
32             if (curSum == sum)
33                 PrintContinuousSequence(small, big);
34         }
35 //        while (curSum <= sum && small < middle) { //自己写的还是不如源码啊。。清晰却不简洁
36 //            big++;
37 //            curSum += big;
38 //            if (curSum >= sum)
39 //                break;
40 //        }
41         big++;
42         curSum += big; //每次更新curSum值
43     }
44 }
45 
46 void PrintContinuousSequence(int small, int big) {
47     for (int i = small; i <= big; ++i)
48         printf("%d ", i);
49 
50     printf("\n");
51 }
52 
53 // ====================测试代码====================
54 void Test(char* testName, int sum) {
55     if (testName != NULL)
56         printf("%s for %d begins: \n", testName, sum);
57 
58     FindContinuousSequence(sum);
59 }
60 
61 int main(int argc, char** argv) {
62     Test("test1", 1);
63     Test("test2", 3);
64     Test("test3", 4);
65     Test("test4", 9);
66     Test("test5", 15);
67     Test("test6", 100);
68 
69     return 0;
70 }

 

—————————————————————————————————————行走在人猿的并行线——Laughing_Lz
posted @ 2016-06-24 19:50  回看欧洲  阅读(185)  评论(0编辑  收藏  举报