欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单计算器

程序员文章站 2022-07-14 08:37:17
...

https://www.lintcode.com/problem/simple-calculator/description

import java.util.HashMap;
import java.util.Map;

public class Calculator {
    /**
     * @param a:        An integer
     * @param operator: A character, +, -, *, /.
     * @param b:        An integer
     * @return: The result
     */
    public int calculate(int a, char operator, int b) {
        // write your code here
        Map<Character, Operate> map = new HashMap<>();
        map.put('+', new Operate() {
            @Override
            public int operate(int x, int y) {
                return x + y;
            }
        });
        map.put('-', new Operate() {
            @Override
            public int operate(int x, int y) {
                return x - y;
            }
        });
        map.put('*', new Operate() {
            @Override
            public int operate(int x, int y) {
                return x * y;
            }
        });
        map.put('/', new Operate() {
            @Override
            public int operate(int x, int y) {
                return x / y;
            }
        });
        Operate operate = map.get(operator);
        return operate.operate(a, b);
    }

    private interface Operate {
        int operate(int x, int y);
    }
}