和为n连续正数序列 【微软面试100题 第五十一题】
来源:互联网 发布:家里网络接线盒没连 编辑:程序博客网 时间:2024/04/30 08:19
题目要求:
输入一个正数n,输出所有和为n连续正数序列(至少两个)。
例如输入15,由于1+2+3+4+5 = 4+5+6 = 7+8 = 15.所以输出3个连续序列1~5,4~6,7~8.
参考资料:剑指offer第41题。
题目分析:
由题意可知:从1~n中找连续的整数序列。
可以用两个变量small和big表示一个区间small~big,再用一个变量sum表示这个区间的数的和如果sum>n,则small向后移,如果sum<n则big向后移,如果sum=n则输出该区间small~big.
代码实现:
#include <iostream>using namespace std;void FindContinuousSequence(int n);int main(void){ int n; cout << "请输入n:"; cin >> n; FindContinuousSequence(n); return 0;}void Print(int small,int big){ cout << "连续序列有:"; for(int i = small;i<=big;i++) cout << i << " "; cout << endl;}void FindContinuousSequence(int n){ //因为至少两个正数,1+2=3,因此如果n<3则不存在连续序列 if(n<3) return; int small = 1; int big = 2; //至少两个数,则最小的数肯定小于mid,作为退出while条件 int mid = (1+n)/2; int curSum = small+big; while(small<mid) { if(curSum==n) Print(small,big); while(curSum>n && small<mid) { curSum -= small; small++; if(curSum==n) Print(small,big); } big++; curSum += big; }}
0 0
- 和为n连续正数序列 【微软面试100题 第五十一题】
- 第五十一题 和为n 连续正数序列
- 【100题】第五十一题 和为n连续正数序列
- 微软等数据结构+算法面试100题(37)-- 和为n 连续正数序列
- 微软100题第51题:和为n连续正数序列
- 微软100题(51)和为n的连续正数序列
- 程序员面试题100题第26题——和为n连续正数序列
- 程序员面试题精选100题(26)-和为n连续正数序列
- 程序员面试题精选100题(26)-和为n连续正数序列
- 程序员面试题精选100题(26)-和为n连续正数序列
- 程序员面试题精选100题(26)-和为n连续正数序列
- 程序员面试题精选100题(26)-和为n连续正数序列[算法]
- 程序员面试题精选100题(26)-和为n连续正数序列[算法]
- 和为n连续正数序列
- 和为n连续正数序列
- 和为n连续正数序列--总结
- 和为n连续正数序列
- 和为n连续正数序列
- jQuery学习笔记3----ajax基础
- 自定义带图片按钮的实现。
- LeetCode OJ 之 Length of Last Word(求最后一个单词的长度)
- 第11周项目6-回文、素数-回文数
- 负值之美:负margin在页面布局中的应用
- 和为n连续正数序列 【微软面试100题 第五十一题】
- 类的成员函数的指针
- C#中的特性 和 通过反射获取属性上的特性
- 学习总结与未来规划
- Native code library failed to load: ensure the appropriate library (opl124.dll/.so) is in your path.
- margin负值原理
- 关于内容泄露问题
- poj1088滑雪(dfs+记忆化搜索、备忘录)
- 栈与队列实验