微软编程一小时活动 - 暨微软2014实习生招募编程模拟测试 题目1 : Arithmetic Expression 原创解答

刚刚完成的答案,已经通过测试,不一定是最好的,但是应该没有太大问题。

希望和大家共同学习,不足之处还望赐教。


此题的版权和最终解释权归出题方所有,欢迎交流学习答案。

题目1 : Arithmetic Expression

时间限制: 2000ms
单点时限: 200ms
内存限制: 256MB

描述

Given N arithmetic expressions, can you tell whose result is closest to 9?

输入

Line 1: N (1 <= N <= 50000).
Line 2..N+1: Each line contains an expression in the format of "a op b" where a, b are integers (-10000 <= a, b <= 10000) and op is one of addition (+), subtraction (-), multiplication (*) and division (/). There is no "divided by zero" expression.

输出

The index of expression whose result is closest to 9. If there are more than one such expressions, output the smallest index.

样例输入
4
901 / 100
3 * 3
2 + 6
8 - -1
样例输出
2
解答代码:

#include <iostream>
using namespace std;

class Expr
{
public:
	int type;
	char *cnum;
	int result;
};
bool numAnd(Expr * num);
int getnumber(char * c);
int main() {
	char c[16];
	int inumcount;
	int index=0;
	int temp;
	int minnum=10000;
	cin.getline(c,10);
	inumcount=getnumber(c);


	Expr  **e=new Expr*[inumcount];
	for (int i=0;i<inumcount;i++)
	{
				cin.getline(c,10);
				e[i]=new Expr();
				e[i]->cnum = new char[strlen(c) + 1];
				if(e[i]->cnum != NULL) 
				{
					strcpy(e[i]->cnum,c);
				}
				e[i]->result=numAnd(e[i]);
	}	
	for (int i=0;i<inumcount;i++)
	{
		temp=e[i]->result-9;
		if (temp<0)
		{
			temp*=-1;
		}
		if (temp<minnum)
		{
			minnum=temp;
			index=i;
		}
	}

		delete []e; 
	cout<<index+1;
	return index+1;
}
int getnumber(char * c)
{

	int result=0,icount=0;
	while (c[icount]>='0'&&c[icount]<='9')
	{
		result*=10;
		result=c[icount]-'0';
		icount++;
	}
	
return result;
}
bool numAnd(Expr * num)
{
	int icount=0;
	int inumber1=0,inumber2=0,iresult=0;
	bool minus=false;
	if ('0'==num->cnum[icount])
	{
				return false;
	}
	while (num->cnum[icount]>='0'&&num->cnum[icount]<='9')
	{
		inumber1*=10;
		inumber1=num->cnum[icount]-'0';
		icount++;
	}
	switch(num->cnum[icount])
	{
	case '+':
		num->type=1;
		break;
	case '-':
		num->type=2;
		break;
	case '*':
		num->type=3;
		break;
	case '/':
		num->type=4;
		break;
	default:
		break;
	}
	icount++;
	if ('0'==num->cnum[icount])
	{
		return false;
	}
	if ('-'==num->cnum[icount])
	{
		minus=true;
		icount++;
	}
	while (num->cnum[icount]>='0'&&num->cnum[icount]<='9')
	{
		inumber2*=10;
		inumber2=num->cnum[icount]-'0';
		icount++;
		if ('\0'==num->cnum[icount])
		{
			break;
		}
		if (0==inumber2&&4==num->type)
		{
			return false;
		}
	}
	inumber2*=-1;
	switch(num->type)
	{
	case 1:
		num->result=inumber1+inumber2;
		break;
	case 2:
		num->result=inumber1-inumber2;
		break;
	case 3:
		num->result=inumber1*inumber2;
		break;
	case 4:
		num->result=inumber1/inumber2;
		break;
	default:
		break;
	}

	return true;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值