public double calc(String exp) {

String regex = MainActivity.PLUSE + "|" + MainActivity.MINUS + "|"

+ MainActivity.MULTIPLY + "|" + MainActivity.DIVIDE;

String[] strings = exp.split(regex);

double[] nums = new double[strings.length];

for (int i = 0; i < nums.length; i++) {

nums[i] = Double.parseDouble(strings[i].trim());

}

List opList = new ArrayList();

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(exp);

while (matcher.find()) {

opList.add(matcher.group());

}

String string;

String[] ops = new String[opList.size()];

for (int i = 0; i < ops.length; i++) {

ops[i] = opList.get(i);

}

double temp;

for (int i = 0; i < ops.length - 1; ++i) {

for (int j = 0; j < ops.length - 1 - i; ++j) {

if (ops[j].compareTo(ops[j + 1]) > 0) {

string = ops[j];

ops[j] = ops[j + 1];

ops[j + 1] = string;

temp = nums[j];

nums[j] = nums[j + 1];

nums[j + 1] = temp;

temp = nums[j + 1];

nums[j + 1] = nums[j + 2];

nums[j + 2] = temp;

}

}

}

double result = nums[0];

StringBuilder builder = new StringBuilder();

for (int i = 0; i < ops.length; i++) {

builder.append(ops[i]);

builder.append(nums[i + 1]);

}

exp = nums[0] + builder.toString();

strings = exp.split(regex);

nums = new double[strings.length];

for (int i = 0; i < nums.length; i++) {

nums[i] = Double.parseDouble(strings[i].trim());

}

for (int i = 0; i < ops.length; ++i) {

if (MainActivity.MULTIPLY.equals(ops[i])) {

nums[0] *= nums[i + 1];

} else if (MainActivity.DIVIDE.equals(ops[i])) {

if (nums[i + 1] != 0) {

nums[0] /= nums[i + 1];

}

} else if (MainActivity.PLUSE.equals(ops[i])) {

nums[0] += nums[i + 1];

} else if (MainActivity.MINUS.equals(ops[i])) {

nums[0] -= nums[i + 1];

}

}

result = nums[0];

return result;

}

算法思想

根据运算符的顺序重新排列数据

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐