NetEase interview questions: And for n consecutive positive numbers sequence (array)
Title: Enter a positive number n to output all and n sequential positive numbers.
For example: Enter 15, because 1+ 2 + 3 + 4 +5 = 4 + 5 + 6 = 7 + 8 = 15, so enter 3 sequential sequences 1,2,3,4,5 and 4,5,6 and 7, 8.
Analysis:
To find a continuous sequence can start from 2 to find, and then find 3, 4 and so on, then when the end?
When the number of K found is found to be less than 1, terminate.
It can also be analyzed that when K is an even number, n*1.0/k = *.5, decimal places must be 5, otherwise find unsuccessful, continue.
Meet the conditions, you will find the first number, the back number.
When k is odd, n*1.0/k =*.0, decimal place must be 0, otherwise find unsuccessful, continue.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Meet the conditions, you will find the first number, the back number.
specifically See implementation:
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std;
void printallsequence (int n) {int k = 2;
while (1) {if (k%2 = = 0) {Float fm = n*1.0/k;
if (INT (FM) < K/2) break;
if (FM!= INT (FM) *1.0 + 0.5) {k++;
Continue
for (int i = INT (FM)-K/2 +1; i <= INT (FM) + K/2; i++) if (i = INT (FM) + K/2)
cout << i << Endl;
else cout << i << ",";
else {Float fm = n*1.0/k;
if (INT (FM) < K/2 + 1) break;
if (FM!= INT (FM) *1.0) {k++;
Continue for (int i = INT (FM)-K/2 i <= INT (FM) + K/2;
i++) if (i = = INT (FM) + K/2) cout << i << Endl;
else cout << i << ",";
K + +;
int main (int argn, char* argv[]) {if (argn >= 2) {int n = atoi (argv[1]);
Printallsequence (n);
return 0; }
Compile:
g++ Test.cpp-o Test
Perform:
./test 15
The result returned is:
7,8
4,5,6
1,2,3,4,5
Postscript:
There is a period of time did not do the problem, feeling quite empty, and continue to work towards the goal forward.
Author: csdn Blog hhh3h