简单计算器
程序员文章站
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);
}
}
上一篇: CListCtrl导出数据到Excel
下一篇: 标题:明码