文章目录
1001、Sum Problem
Code:
1、注意:输出格式的要求,因为题目要求空一行,所以需要cout<<endl<<endl;
2、计算从1-n的和并输出
#include<iostream>
using namespace std;
int main() {
int n,sum;
while (cin >> n) {
sum = 0;
if (n == 0) return 0;
for (int i = 1; i <= n; i++) {
sum = sum + i;
}
cout << sum << endl<<endl;
}
}
1004、 Let the Ballon Rise
Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) – the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.
A test case with N = 0 terminates the input and this test case is not to be processed.
Output
For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.
Sample Input
5
green
red
blue
red
red
3
pink
orange
pink
0
Sample Output
red
pink
Code:
1、二维数组输入字符串,字符串的长度有限定
2、strcmp()函数
3、比较数组中元素相同的个数
#include<iostream>
using namespace std;
int main() {
int n;
while (cin >> n) {
if (n == 0) return 0;
int num[1000] = {
0};
char color[1000][15];//借用二维数组输入字符串
for (int i = 0; i < n; i++) {
cin >> color[i];
}
//寻找color[]中个数最多的元素
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(color[i], color[j]) == 0) {
//strcmp()字符串比较函数
num[i]++;
}
}
}
int max =0;
for (int i = 1; i < n; i++) {
if (num[i] > max)
max = i;
}
cout << color[max] << endl;
}
}
1005、 Number Sequence
Problem Description
A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
0 0 0
Sample Output
2
5
Code:
方法一:使用递归的方式,但会出现内存超限的问题
#include<iostream>
using namespace std;
int f(int a, int b, int n) {
int result;
if (n == 1||n==2) {
return 1;
}
else {
result=(a * f(a,b,n - 1) + b *