华为笔试——C++字符串四则运算的实现--C++ 递归实现

华为笔试——C++字符串四则运算的实现

题目:字符串四则运算的实现

有字符串表示的一个四则运算表达式,要求计算出该表达式的正确数值。四则运算即:加减乘除"+-*/",另外该表达式中的数字只能是1位(数值范围0~9),运算不用括号。另若有不能整除的情况,按向下取整处理,eg: 8/3得出值为2。

举例:字符串"8+7*2-9/3",计算出其值为19。

规则:不能带有括号。

具体题目,我没有看到,只是按照我的理解来写的源码,希望可以对你有帮助。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<string>
using namespace std;



// 8+7*2-9/3
int compute(string str)
{
	int pos = -1;
	if ( (pos = str.find('+',0)) != -1)
	{
		string str1 = str.substr(0, pos);
		string str2 = str.substr(pos + 1);

		return compute(str1) + compute(str2);
	}
	if ((pos = str.find('-', 0)) != -1)
	{
		string str1 = str.substr(0, pos);
		string str2 = str.substr(pos + 1);

		return compute(str1) - compute(str2);
	}

	if ((pos = str.find('*', 0)) != -1)
	{
		string str1 = str.substr(0, pos);
		string str2 = str.substr(pos + 1);

		return compute(str1) * compute(str2);
	}

	if ((pos = str.find('/', 0)) != -1)
	{
		string str1 = str.substr(0, pos);
		string str2 = str.substr(pos + 1);

		return compute(str1) / compute(str2);
	}
	return atoi(str.c_str());
	
}

int main()
{
	
	string str = "8+7*2-9/3";
	int ret = compute(str);
	cout << ret << endl;
}

第一个版本,写出来后,发现代码太冗余了。后面又改善了一个版本。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<string>
using namespace std;


int cal(char ch, int data1, int data2)
{
	switch (ch)
	{
	case '+':
		return data1 + data2;
	case '-':
		return data1 - data2;
	case '*':
		return data1 * data2;
	case '/':
		return data1 / data2;
	default:
		return data1 + data2;
	}
}



// 8+7*2-9/3
int compute2(string str)
{
	int pos = -1;
	if ((pos = str.find('+', 0)) != -1  
               || (pos = str.find('-', 0)) != -1 
               || (pos = str.find('*', 0)) != -1 
               || (pos = str.find('/', 0)) != -1)
	{
		string str1 = str.substr(0, pos);
		string str2 = str.substr(pos + 1);
		return cal(str[pos], compute2(str1), compute2(str2));
	}
	
	return atoi(str.c_str());

}

int main()
{
        string str = "8+7*2-9/3";
	int ret1 = compute2(str);
	cout << ret1 << endl;
	return 0;
}

注意:对于异常情况没有处理,例如 除以0啊,或者 含有其他字符,

猜你喜欢

转载自blog.csdn.net/qd1308504206/article/details/84943827