Chinaunix首页 | 论坛 | 博客
  • 博客访问: 616515
  • 博文数量: 263
  • 博客积分: 9025
  • 博客等级: 中将
  • 技术积分: 2557
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-01 17:42
文章分类

全部博文(263)

文章存档

2012年(4)

2011年(64)

2010年(47)

2009年(44)

2008年(99)

2007年(5)

我的朋友

分类: C/C++

2011-04-28 16:43:15

题目:输入一个正数n,输出所有和为n连续正数序列。

例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-54-67-8

分析:这是网易的一道面试题。

这道题和本面试题系列的第10有些类似。我们用两个数smallbig分别表示序列的最小值和最大值。首先把small初始化为1big初始化为2。如果从smallbig的序列的和大于n的话,我们向右移动small,相当于从序列中去掉较小的数字。如果从smallbig的序列的和小于n的话,我们向右移动big,相当于向序列中添加big的下一个数字。一直到small等于(1+n)/2,因为序列至少要有两个数字。

基于这个思路,我们可以写出如下代码:

void PrintContinuousSequence(int small, int big);

/////////////////////////////////////////////////////////////////////////
// Find continuous sequence, whose sum is n
/////////////////////////////////////////////////////////////////////////
void FindContinuousSequence(int n)
{
      if(n < 3)
            return;

      int small = 1; 
      int big = 2;
      int middle = (1 + n) / 2;
      int sum = small + big;

      while(small < middle)
      {
            // we are lucky and find the sequence
            if(sum == n)
                  PrintContinuousSequence(small, big);

            // if the current sum is greater than n, 
            // move small forward
            while(sum > n)
            {
                  sum -= small;
                  small ++;

                  // we are lucky and find the sequence
                  if(sum == n)
                        PrintContinuousSequence(small, big);
            }

            // move big forward
            big ++;
            sum += big;
      }
}

/////////////////////////////////////////////////////////////////////////
// Print continuous sequence between small and big
/////////////////////////////////////////////////////////////////////////
void PrintContinuousSequence(int small, int big)
{
      for(int i = small; i <= big; ++ i)
            printf("%d ", i);

      printf("\n");
}

阅读(562) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~