您的位置:首页 > 编程语言 > Java开发

java实现四则运算,难点主要在理解加减乘除优先级以及使用递归

2016-01-07 16:02 791 查看
采用递归的方式实现基本的四则运算。

首先弄清楚四则运算的优先级,比如一个混杂加法和减法的式子,减法的优先级要高于加法,也就是你从左往右算,先算减法是正确的,先算加法会得到错误的答案。比如3-2+1,先算加法,得到的结果是0。

同理,除法优先级高于乘法,乘法优先级高于减法。

而在递归运算中,是递归底层计算后,一层层把结果往外翻,所以,应该解析顺序应该是:加、减、乘、除。与优先级刚好相反。理解了这里基本就可以完成四则运算的算法了。

下面是代码实现(增加了括号的处理):

import java.math.BigDecimal;

public class CalculateNum {

public BigDecimal cal(String str) {
if (str == null) {
return null;
}

String fuhao = "";
int index = 0;

str = str.replaceAll("--", "+"); // 等价替换;
str = str.replaceAll(" ", ""); // 去掉空格

fuhao = "(";
index = str.lastIndexOf(fuhao);
if (index >= 0) {
int rightIndex = str.indexOf(")", index);

String left = str.substring(0, index);
String right = "";
if (rightIndex + 1 < str.length()) {
right = str.substring(rightIndex + 1);
}

BigDecimal middle = cal(str.substring(index + 1, rightIndex));
return cal(left + middle + right);
}

fuhao = "+";
index = str.lastIndexOf(fuhao);
if (index > 0) {
BigDecimal left = cal(str.substring(0, index));
BigDecimal right = cal(str.substring(index + 1));
return left.add(right);
}

fuhao = "-";
index = str.lastIndexOf(fuhao);
if (index == 0) { // 负数处理
BigDecimal result = cal(str.substring(index + 1));
if (result.compareTo(new BigDecimal("0")) == -1) { // 小于0
return result.abs(); // 绝对值
} else {
return result.negate(); // 相反数
}
} else if (index > 0) {
BigDecimal left = cal(str.substring(0, index));
BigDecimal right = cal(str.substring(index + 1));
return left.subtract(right);
}

fuhao = "*";
index = str.lastIndexOf(fuhao);
if (index > 0) {
BigDecimal left = cal(str.substring(0, index));
BigDecimal right = cal(str.substring(index + 1));
return left.multiply(right);
}

fuhao = "/";
index = str.lastIndexOf(fuhao);
if (index > 0) {
BigDecimal left = cal(str.substring(0, index));
BigDecimal right = cal(str.substring(index + 1));
return left.divide(right);
}

return new BigDecimal(str);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息