输入一个正数n,输出所有和为n连续正数序列。
来源:互联网 发布:人工智能7大应用领域 编辑:程序博客网 时间:2024/04/25 10:14
题目:输入一个正数n,输出所有和为n连续正数序列。
例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。
分析:这是网易的一道面试题。
这道题和本面试题系列的第10题有些类似。我们用两个数small和big分别表示序列的最小值和最大值。首先把small初始化为1,big初始化为2。如果从small到big的序列的和大于n的话,我们向右移动small,相当于从序列中去掉较小的数字。如果从small到big的序列的和小于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 thesequence
if(sum == n)
PrintContinuousSequence(small, big);
// if the current sum is greater thann,
// move small forward
while(sum > n)
{
sum -= small;
small ++;
// we are lucky and find thesequence
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");
}
- 输入一个正数n,输出所有和为n连续正数序列。
- 输入一个正数n,输出所有和为n连续正数序列。
- 输入一个正数n,输出所有和为n 连续正数序列
- 输入一个正数 n,输出所有和为 n 的连续正数序列 [No. 25]
- 【每日面试题】输入一个正数n,输出所有和为n连续正数序列
- 输入一个正数n,输出所有和为n连续正数序列
- 输入一个正数 n,输出所有和为n 连续正数序列。
- 输入一个正数n,输出所有和为n连续正数序列。
- 输入一个正数 n,输出所有和为 n 连续正数序列。
- 输入一个正数n,输出所有和为n连续正数序列
- 输入一个正数n,输出所有和为n连续正数序列。
- 算法习题51:输入一个正数n,输出所有和为n连续正数序列
- 输入一个正数n,输出所有和为n 连续正数序列
- 输入一个正数n,输出所有和为n 连续正数序列
- 输入一个正数n,输出所有和为n的连续正数序列
- 【算法学习-01】 输入一个正数 n,输出所有和为 n 连续正数序列。
- 网易面试题 输入一个正数n,输出所有和为n连续正数序列
- 输入一个正数n,输出所有和为n连续正整数序列
- Linux系统分区和挂载浅谈
- HOST: 239.255.255.250:1900
- 修改netbox
- 使用javaScript和DOM操作svg元素
- Google Chrome 浏览器无法运行 Applet 的解决方法
- 输入一个正数n,输出所有和为n连续正数序列。
- 提升安全性WindowsXP必禁的十大服务
- 塔吊的安装
- oracle的常用命令
- 魔兽世界模型文件.m2 在D3D下的渲染
- 个人网页中必不可少的十五大Web API
- 正确的在网页中插入flash
- 不可战胜(亨利)
- 寻找生命的目标