1. 程式人生 > >華為筆試——C++字串四則運算的實現--C++ 遞迴實現

華為筆試——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啊,或者 含有其他字元,