PAT-BASIC1049——数列的片段和/PAT-ADVANCED1104——Sum of Number Segments

本文详细介绍了PAT考试中两道题目——1049数列的片段和与1104Sum of Number Segments的解题思路,重点在于寻找规律。通过C++实现,时间复杂度为O(n),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC

我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED

原题链接:

PAT-BASIC1049:https://pintia.cn/problem-sets/994805260223102976/problems/994805275792359424

PAT-ADVANCED1104:https://pintia.cn/problem-sets/994805342720868352/problems/994805363914686464

题目描述:

PAT-BASIC1049:

PAT-ADVANCED1104:

知识点:数学

思路:找规律

假设所给数组的长度为n。对于索引为i的元素,其出现次数是(n - i) * (i + 1)。注意int型数据会越界,需要用long型数据。

时间复杂度是O(n)。空间复杂度是O(1)。

C++代码:

#include<iostream>
#include<vector>

using namespace std;

int main(){
	long n;
	cin >> n;
	
	vector<double> nums;
	double tempNum;
	
	for(int i = 0; i < n; i++){
		cin >> tempNum;
		nums.push_back(tempNum);
	}
	
	long count[n];
	for(int i = 0; i < n; i++){
		count[i] = (n - i) * (i + 1);
	}

	
	double result = 0.0;
	for(int i = 0; i < n; i++){
		result += count[i] * nums[i];
	}
	
	printf("%.2f", result);
	
	return 0;
}

C++解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值