字符串四則運算

最近做了一道華爲的機試題。感覺自己的方法比網上的簡潔。

3. 簡單四則運算
問題描述:
輸入一個只包含個位數字的簡單四則運算表達式字符串,計算該表達式的值

1、表達式只含 +, -, *, / 四則運算符,不含括號
2、表達式數值只包含個位整數(0-9),且不會出現0作爲除數的情況
3、要考慮加減乘除按通常四則運算規定的計算優先級
4、除法用整數除法,即僅保留除法運算結果的整數部分。比如8/3=2。輸入表達式保證無0作爲除數情況發生
5、輸入字符串一定是符合題意合法的表達式,其中只包括數字字符和四則運算符字符,除此之外不含其它任何字符,不會出現計算溢出情況

要求實現函數:
int calculate(int len,char *expStr)

【輸入】  int len: 字符串長度;
char *expStr: 表達式字符串;
【輸出】  無
【返回】  計算結果

示例
1)  輸入:char *expStr = “1+4*5-8/3”
函數返回:19
2)  輸入:char *expStr = “8/3*3”
函數返回:6*/


#include <stdio.h>
#include <memory>
#include <string.h>
/*****************************************/
//這個算法開闢了額外的空間。
//分析這個問題可以知道,字符串長度len是奇數(0不考慮)
//數字的個數是len/2+1,符號的個數爲len/2,然後將符號和數字存儲起來
//第一步處理所有的乘除法,此時有一個特點就是如果幾個數
//連續進行乘除法的時候就需要向前存儲結果(爲了方便後面的加減法運算)
//算法複雜度O(n)
/*****************************************/
int calculate(int len,char *expStr)
{	
	int i,j,k,answer;
	int* num=(int*)malloc((len/2+1)*sizeof(int));
	char* exp=(char*)malloc(len/2);
	for (i=0,j=0,k=0;i<len;i++)          //將符號和數字分開存儲
	{
		if(i%2==0)
			num[j++]=expStr[i]-'0';
		else
			exp[k++]=expStr[i];
	}
	//乘除法處理
	for (i=0,j=1;i<len/2;i++)
	{
		if (exp[i]!='*'&&exp[i]!='/')
		{
			j=1;
			continue;
		}
		if (exp[i]=='*')
		{
			num[i+1]*=num[i];
			for (k=0;k<j;k++)
			{
				num[i-k]=num[i+1];
			}
			j++;
		}
		else if (exp[i]=='/')
		{
			num[i+1]=num[i]/num[i+1];
			for (k=0;k<j;k++)
			{
				num[i-k]=num[i+1];
			}
			j++;
		}
	}
	//處理加減法
	answer=num[0];
	for (i=0,j=1;i<len/2;i++)
	{
		if (exp[i]=='+')
			answer+=num[i+1];
		else if (exp[i]=='-')
			answer-=num[i+1];
	}
	return answer;
}

int main()
{
	char* a="1+4*5-8/3*2*2*2";
	int result=calculate(strlen(a),a);
	//int result=calculate2(strlen(a),a);
	printf("%d",result);
	return 0;
}

//網上的答案,用棧進行操作
int calculate2(int len,char *expStr)  
{  
    struct  {  
        char opdata[200];  
        int top;  
    }opstack;  
    //定義操作符棧   
  
    opstack.top = -1;  
  
    int i=0;//遍歷字符串的下標   
    int t=0;//當前後綴表達式的長度   
  
    char ch = expStr[i];  
  
    while (ch!='\0')  
    {  
        switch (ch)  
        {  
            case '+':  
            case '-':  
			   while (opstack.top != -1)  
			   {  
                    expStr[t] = opstack.opdata[opstack.top];  
                    opstack.top--;  
                    t++;  
                }  
                opstack.top++;  
               opstack.opdata[opstack.top] = ch;  
                break;  
            case '/':  
                while (opstack.top != -1 && (opstack.opdata[opstack.top] =='*' || opstack.opdata[opstack.top] =='/') )  
                {  
                    expStr[t] = opstack.opdata[opstack.top];  
                    opstack.top--;  
                    t++;  
                }  
                opstack.top++;  
                opstack.opdata[opstack.top] = ch;  
                break;  
            default:  
                expStr[t] = ch;  
                t++;  
                break;  
        }  
        i++;  
        ch = expStr[i];  
    }  
  
    while (opstack.top != -1)//將棧中所有的剩餘的運算符出棧   
    {  
        expStr[t] = opstack.opdata[opstack.top];  
        opstack.top--;  
        t++;  
    }  
  
    expStr[t]='\0';  
  
  
    struct  {  
        int numeric[200];  
        int top;  
    }data;  
  
    data.top = -1;  
  
    i=0;  
    ch = expStr[i];  
  
  
    while (ch!='\0')  
    {  
        if (ch>='0' && ch <= '9' )  
        {  
            data.top++;  
            data.numeric[data.top] = ch-'0';  
        }   
        else if('+' == ch)  
        {  
            int tmp = data.numeric[data.top-1]  + data.numeric[data.top];  
            data.top--;  
            data.numeric[data.top] = tmp;  
        }  
        else if('-' == ch)  
        {  
            int tmp = data.numeric[data.top-1]  - data.numeric[data.top];  
            data.top--;  
            data.numeric[data.top] = tmp;  
        }  
        else if('*' == ch)  
        {  
            int tmp = data.numeric[data.top-1]  * data.numeric[data.top];  
            data.top--;  
            data.numeric[data.top] = tmp;  
        }  
        else if('/' == ch)  
       {  
            if(data.numeric[data.top] == 0)  
            {  
                printf("cannot be zero of the divide\n");  
                exit(1);  
            }  
            int tmp = data.numeric[data.top-1] / data.numeric[data.top];  
            data.top--;  
            data.numeric[data.top] = tmp;  
        }  
        i++;  
        ch = expStr[i];  
    }  
  
    return data.numeric[data.top];  
}


發佈了38 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章