**四则运算

题目描述:

四则运算

输入描述:

输入一个算术表达式

输出描述:

得到计算结果

思路:

栈的应用:

中缀表达式转后缀表达式:

规则:从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,即成为后缀表达式的一部分;若是符号,则判断其与栈顶符号的优先级,是右括号或优先级不高于栈顶符号(乘除优先加减)则栈顶元素依次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。

后缀表达式计算结果:

规则:从左到右遍历表达式的每个数字和符号,遇到是数字就进栈,遇到是符号,就将处于栈顶两个数字出栈,进行运算,运算结果进栈,一直到最终获得结果。

1、多位数

2、负数

import java.util.*;

public class Main
{

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            String str = scanner.nextLine();
            str = convert(str); //若'-'表示负数,在前面加上0
            ArrayList suffix = infixToSuffix(getExpress(str)); //中缀变后缀表达式
            int num = suffixToNum(suffix); //计算后缀表达式
            System.out.println(num);
        }
    }
    public static String convert(String str)
    {
        for (int i = 0; i < str.length(); i++)
        {
            if (i == 0 && str.charAt(i) == '-')
                str = "0" + str;
            else if (i > 0 && str.charAt(i) == '-' && !(str.charAt(i - 1) >= '0' && str.charAt(i - 1) <= '9') && str.charAt(i - 1) != ')')
                str = str.substring(0, i) + "0" + str.substring(i);
        }
        return str;
    }

    public static String getExpress(String str)
    {
        str = str.replace('{', '(');
        str = str.replace('[', '(');
        str = str.replace('}', ')');
        str = str.replace(']', ')');

        StringBuffer sb = new StringBuffer();
        for (char c: str.toCharArray()) //在运算符前后加上空格,以便区别
        {
            if (c == '(' || c== ')' || c == '+' || c == '-' || c == '*' || c == '/')
            {
                sb.append(" ");
                sb.append(c);
                sb.append(" ");
            }
            else
                sb.append(c);
        }
        String res = sb.toString().trim();
        return res;
    }


    public static ArrayList infixToSuffix(String str)
    {
        String[] strs = str.split("\\s+");

        ArrayList list = new ArrayList<>();
        Stack stack = new Stack<>();
        for (String s: strs)
        {
            switch (s)
            {
                case "(":
                    stack.push(s);
                    break;
                case "+":
                case "-":
                    while (!stack.isEmpty())
                    {
                        String tmp = stack.pop();
                        if (tmp.equals("(")) {
                            stack.push(tmp);
                            break;
                        }
                        else
                            list.add(tmp);
                    }
                    stack.push(s);
                    break;
                case "*":
                case "/":
                    while (!stack.isEmpty())
                    {
                        String tmp = stack.pop();
                        if (tmp.equals("(") || tmp.equals("+") || tmp.equals("-"))
                        {
                            stack.push(tmp);
                            break;
                        }
                        else
                            list.add(tmp);
                    }
                    stack.push(s);
                    break;
                case ")":
                    while (!stack.isEmpty())
                    {
                        String tmp = stack.pop();
                        if (tmp.equals("("))
                            break;
                        else
                            list.add(tmp);
                    }
                    break;
                default:
                    list.add(s);
                    break;
            }
        }
        while (!stack.isEmpty())
            list.add(stack.pop());
        return list;
    }

    public static int suffixToNum(ArrayList list)
    {
        Stack stack = new Stack<>();
        for (String s: list)
        {
            if (s.charAt(0) >= '0' && s.charAt(0) <= '9')
                stack.push(Integer.valueOf(s));
            else if (stack.size() >= 2)
            {
                int num1 = stack.pop();
                int num2 = stack.pop();
                switch (s)
                {
                    case "+":
                        stack.push(num2 + num1);
                        break;
                    case "-":
                        stack.push(num2 - num1);
                        break;
                    case "*":
                        stack.push(num2 * num1);
                        break;
                    case "/":
                        stack.push(num2 / num1);
                        break;
                }
            }
        }
        return stack.pop();
    }
}

你可能感兴趣的:(华为机试,字符串)