華為編程大賽初賽試題-簡單四則運算

來源:互聯網
上載者:User

簡單四則運算

註: 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

PS:網上有看到使用棧來實現。自己琢磨著用遞迴分治來實現,其實也類似棧的原理

// _huawei_9_12.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stdio.h>#include <string.h>#define NUM (1<<30)int calculate(int len,char *expStr){int process(int,int ,char*);int end=process(0,len-1,expStr);return end;}int process(int begin,int end,char *expStr){int i,result=1;if(begin==end){result=expStr[end]-'0';return result;}//else if(begin+1=end)for(i=begin;i<end&&expStr[i]!='\0';i++){if(expStr[i]=='+'){result=process(begin,i-1,expStr)+process(i+1,end,expStr);return result;}else if(expStr[i]=='-'){result=process(begin,i-1,expStr)-process(i+1,end,expStr);return result;}}if(expStr[begin]!='\0')result=expStr[begin]-'0';for(i=begin;i<end&&expStr[i]!='\0';i++){if(expStr[i]=='*'){ result=result*(expStr[i+1]-'0');}else if(expStr[i]=='/')result=result/(expStr[i+1]-'0');}//result=expStr[i]-'0';printf("**********%d\n",result);return result;}int main(int argc, char* argv[]){char *expStr = "1+4*5-8/3*6/5*7*2-3+0";int len=strlen(expStr);printf("%d\n",calculate(len,expStr));return 0;}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.