2011华为校园招聘重庆试题第三题

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

public int calculate(String str,int len) {

for(int i=0;i<str.length();i++){
if(Character.isDigit(str.charAt(i))){
if(numstack.isEmpty()){
numstack.push(String.valueOf(str.charAt(i)));
}else if(operstack.peek().equals("+")||operstack.peek().equals("-")){
numstack.push(String.valueOf(str.charAt(i)));
}else if(operstack.peek().equals("*")){
operstack.pop();
int oper1=Integer.parseInt(String.valueOf(str.charAt(i)));
int oper2=Integer.valueOf(numstack.pop());
int temp=oper1*oper2;
numstack.push(String.valueOf(temp));
}else{
operstack.pop();
int oper1=Integer.parseInt(String.valueOf(str.charAt(i)));
int oper2=Integer.valueOf(numstack.pop());
int temp=oper2/oper1;
numstack.push(String.valueOf(temp));
 
}
}else{
operstack.push(String.valueOf(str.charAt(i)));
}
}
 
while(!operstack.isEmpty()){
String temp=operstack.pop();
if(temp.equals("+")){
int oper1=Integer.parseInt(numstack.pop());
int oper2=Integer.parseInt(numstack.pop());
int result=oper1+oper2;
numstack.push(String.valueOf(result));
}else{
int oper1=Integer.parseInt(numstack.pop());
int oper2=Integer.parseInt(numstack.pop());
int result=oper2-oper1;
numstack.push(String.valueOf(result));
}
}
int result=Integer.parseInt(numstack.pop());
return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值