亚马逊笔试题1

1.

Question:

Given an array with positive integers and another integer for example{7 2 4} 9, you are required to generate an equation, by inserting operator add ("+") and minus ("-") among the array . The left side of equation are consist of the array and the right side of equation is the integer. here the result is 7-2+4=9

 

Rules:

Don't include any space in the generated equation.
In case there is no way to create the equation, please output "Invalid". For example {1 1} 10, output is "Invalid"
The length of the integer array is from 1 to 15( include 1 and 15). If the length is 1, for example the input  {7} 7, the output is 7=7
There is no operator "+" or "-" in front of the first number: 
Don't change the order of the numbers. For example:  {7 2 4}  9. 7-2+4=9 is correct answer, 4-2+7=9 is wrong answer.
There could be multiple input, meaning your function could be called multiple times. Do remember print a new line after the call.  

Sample Input and Output:

Input:

1 2 3 4 10

1 2 3 4 5

Output:

1+2+3+4=10

Invalid

-----------------------------------------

#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

/************************************************************************/
/**
Args:
array[]: the inputted array
final: the target value
length: the element length
*/

void createEquationAndPrint(int array[], int length, int final){
	//Your Code is here
	if(length == 1)
		if(array[0] == final)
		{
			cout<<array[0]<<"="<<final;
			return;
		}
		else if(array[0] != final)
		{
			cout<<"Invalid";
			return;
		}
	
	int iMax = 1<<(length-1);
	vector<char> v;
	v.resize(length - 1);
	int res = 0;
	bool isFind = false;
	for(int i = 0; i < iMax; i++)
	{
		res = array[0];
		for(int j = 0; j < length - 1; j++)
		{
			if((i & (1 << j)) == 0)
			{
				v[j] = '+';
				res += array[j + 1];
			}
			else
			{
				v[j] = '-';
				res -= array[j + 1];
			}
		}

		if(res == final)
		{
			for(int k = 0; k < length - 1; k++)
				cout<<array[k]<<v[k];
			cout<<array[length - 1]<<"="<<final;
			isFind = true;
			break;
		}
	}

	if(!isFind)
		cout<<"Invalid";
	
}



int splitAndConvert(char* strings,int array[]){
	char*tokenPtr = strtok(strings," ");
	int i=0;
	while(tokenPtr!=NULL){
		array[i] = atoi(tokenPtr);
		i++;
		tokenPtr=strtok(NULL," ");
	}
	return i;
}

int main(){
	char line[1000] = {0} ;
	while(gets(line)){
		int array[30] = {0};
		int length = splitAndConvert(line,array);
		if(length==0){
			break;
		}
		createEquationAndPrint(array, length-1, array[length-1]);
		cout<<endl;
	}
	return 0; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值