跳到主要内容

1006.笨阶乘

链接:1006.笨阶乘
难度:Medium
标签:栈、数学、模拟
简介:给定一个整数 N,它返回 N 的笨阶乘。

题解 1 - typescript

  • 编辑时间:2021-04-01
  • 执行用时:112ms
  • 内存消耗:45.8MB
  • 编程语言:typescript
  • 解法介绍:先算出模板,再利用模板进行运算。
const op = ['*', '/', '+', '-'];
const opMap: Record<string, (num1: number, num2: number) => number> = {
'*': (num1, num2) => num1 * num2,
'/': (num1, num2) => ~~(num1 / num2),
'+': (num1, num2) => num1 + num2,
'-': (num1, num2) => num1 - num2,
};
function clumsy(N: number): number {
let curOp = 0;
const template: (number | string)[] = [];
while (N) {
template.push(N--);
template.push(op[curOp]);
curOp = (curOp + 1) % 4;
}
template.pop();
const stack: (number | string)[] = [];
for (let i = 0, l = template.length; i < l; i++) {
const c = template[i];
if (c === '*' || c === '/') {
const num1 = stack.pop() as number;
const num2 = template[++i] as number;
stack.push(opMap[c](num1, num2));
} else stack.push(c);
}
template.length = 0;
template.push(...stack);
stack.length = 0;
for (let i = 0, l = template.length; i < l; i++) {
const c = template[i];
if (c === '+' || c === '-') {
const num1 = stack.pop() as number;
const num2 = template[++i] as number;
stack.push(opMap[c](num1, num2));
} else stack.push(c);
}
return stack[0] as number;
}