LC.P1006[笨阶乘]

方法一:栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int clumsy(int n) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(n--);
int index = 0; // * / + -
while (n > 0) {
if (index % 4 == 0) {
stack.push(stack.pop() * n);
} else if (index % 4 == 1) {
stack.push(stack.pop() / n);
} else if (index % 4 == 2) {
stack.push(n);
} else {
stack.push(-n);
}
++index;
--n;
}
int ans = 0;
while (!stack.isEmpty()) {
ans += stack.pop();
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$