二十四点(ccf 201903-2)

03-12 1187阅读

该题考察表达式计算,可以用Stack实现

二十四点(ccf 201903-2)
(图片来源网络,侵删)

具体代码

import java.util.*;
public class Main7 {
    public static Map map = new HashMap();
    public static boolean isOp(char c){
        if(c=='+' || c=='-' ||c=='x' ||c=='/'){
            return true;
        }
        else{
            return false;
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        sc.nextLine();
        List exprLst = new ArrayList();
        for(int i = 0; i  map.get(stack.peek())){
                            stack.push(c);
                        }
                        else{
                            while (!stack.isEmpty() && map.get(c) 
                                char op = stack.pop();
                                sb.append(op);
                            }
                            stack.push(c);
                        }
                    }
                }
            }
            while (!stack.isEmpty()){
                sb.append(stack.pop());
            }
//            System.out.println(sb);
            char[] postArr = sb.toString().toCharArray();
            for(char c : postArr){
                if(!isOp(c)){
                    compStack.push(String.valueOf(c));
                }
                else{
                    int b = Integer.parseInt(compStack.pop());
                    int a = Integer.parseInt(compStack.pop());
                    switch (c){
                        case '+':
                            compStack.push(String.valueOf(a+b));
                            break;
                        case '-':
                            compStack.push(String.valueOf(a-b));
                            break;
                        case 'x':
                            compStack.push(String.valueOf(a*b));
                            break;
                        case '/':
                            compStack.push(String.valueOf(a/b));
                            break;
                        default:
                            break;
                    }
                }
            }
//            System.out.println(compStack.pop());
            if(Integer.parseInt(compStack.pop()) == 24){
                System.out.println("Yes");
            }
            else{
                System.out.println("No");
            }
        }
    }
}
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]