上次偶尔看到一个面试题是四则运算,了解了一下算法用java实现,如下
package test;
import java.util.*;
public class Szys {
public static void main(String[] args) {
Szys szys = new Szys();
szys.szysTest();
}
public void szysTest() {
System.out.println("输入表达式:");
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
str1 = str1 + "@";
StringBuilder sb = new StringBuilder();
MyStack opstack = new MyStack();
opstack.push('@');
int len = str1.length();
char ch;
char ch1;
char ch2;
//中缀表达式转化为后缀表达式
for (int i = 0; i < len; i++) {
ch = str1.charAt(i);
if (isOperator(ch)) {
ch1 = (Character) opstack.peek();
if (ch == ')') {
ch2 = (Character) opstack.pop();
while (ch2 != '(') {
sb.append(' ');
sb.append(ch2);
ch2 = (Character) opstack.pop();
}
} else if (ch == '(') {
opstack.push(ch);
} else if (ch == '@') {
ch2 = (Character) opstack.pop();
while (ch2 != '@') {
sb.append(' ');
sb.append(ch2);
ch2 = (Character) opstack.pop();
}
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
while (priority(ch1) >= priority(ch)) {
sb.append(' ');
sb.append(ch1);
opstack.pop();
ch1 = (Character) opstack.peek();
}
opstack.push(ch);
}
} else {
sb.append(' ');
sb.append(ch);
}
}
System.out.println(sb.toString());
operation(sb.toString());
}
//设置符号优先级
public int priority(char operator) {
int i = 0;
if ('+' == operator || '-' == operator) {
i = 1;
} else if ('*' == operator || '/' == operator) {
i = 2;
} else if ('@' == operator || '(' == operator) {
i = 0;
}
return i;
}
public boolean isOperator(char operator) {
boolean flag = false;
if ('+' == operator || '-' == operator || '*' == operator
|| '/' == operator || '(' == operator || ')' == operator || '@' == operator) {
flag = true;
}
return flag;
}
//用于运算,一个运算符运算完将结果放入栈中
public void operation(String tmpStr){
MyStack tmpStack = new MyStack();
String[] tmpStrArr = tmpStr.split(" ");
String tmpStr1 = "",tmpStr2 = "",tmpStr3 = "";
float tmpFloat = 0,tmpFloat1 = 0,tmpFloat2 = 0;
for(String str:tmpStrArr){
if("+".equals(str)||"-".equals(str)||"*".equals(str)||"/".equals(str)){
tmpStr1 = (String)tmpStack.pop();
tmpStr2 = (String)tmpStack.pop();
tmpFloat1 = Float.parseFloat(tmpStr1);
tmpFloat2 = Float.parseFloat(tmpStr2);
if("+".equals(str)){
tmpFloat = tmpFloat2 + tmpFloat1;
}else if("-".equals(str)){
tmpFloat = tmpFloat2 - tmpFloat1;
}else if("*".equals(str)){
tmpFloat = tmpFloat2 * tmpFloat1;
}else if("/".equals(str)){
tmpFloat = tmpFloat2 / tmpFloat1;
}
tmpStr3 = String.valueOf(tmpFloat);
tmpStack.push(tmpStr3);
}else{
tmpStack.push(str);
}
}
System.out.println(tmpStack.peek());
}
}
栈的实现,网上很多
package test;
import java.util.LinkedList;
//LinkedList实现栈
public class MyStack {
private LinkedList<Object> ll = new LinkedList<Object>();
public void push(Object o){
ll.addFirst(o);
}
public Object pop(){
return ll.removeFirst();
}
public Object peek(){
return ll.getFirst();
}
public boolean empty(){
return ll.isEmpty();
}
public void show(){
for(int i=ll.size()-1;i>=0;i--){
System.out.print(ll.get(i));
}
System.out.println();
}
}