2019盛趣笔试编程题

2019盛趣笔试编程题

输入n个整数,第一个数为x,余下的数构成一个数组,求x与余下数最相近的三个数的和.

输入

2 3 6 7 -1

输出

8 (说明:3+6-1=8)

直接贴代码了

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <math.h>

using namespace std;

int n[3];
//找出最相近的三个数中最不相近的数字
int MaxInSelects(int firstNum)
{
	int max = 0;
	for (int i=1;i<3;i++)
	{
		if (abs(n[max]-firstNum) < abs(n[i]-firstNum))
			max= i;
	}
	return max;
}

int Sum(int firstNum,vector<int> nums) {
	if (nums.size()<3)
	{
		return NULL;
	}
	
	for (int i = 0; i < 3; i++)
	{
		n[i] = nums.back();
		nums.pop_back();
	}
	int tempIndex;
	for each (int vNum in nums)
	{
		tempIndex = MaxInSelects(firstNum);
		if (abs(n[tempIndex] - firstNum) > abs(vNum - firstNum))
			n[tempIndex] = vNum;
	}
	return n[0] + n[1] + n[2];
}
int main() {
	int firstNum;
	cin >> firstNum;
	vector<int> nums;
	int tempNum;
	char getChar='a';
	//只接受一行输入
	while (~scanf_s("%d%c",&tempNum,&getChar))
	{
		nums.push_back(tempNum);
		if (getChar == '\n')
			break;
	}
	cout << Sum(firstNum, nums);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值