# 1006. Clumsy Factorial

## Description

The factorial of a positive integer n is the product of all positive integers less than or equal to n.

• For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.

We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order.

• For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.

However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.

Given an integer n, return the clumsy factorial of n.

Example 1:

Input: n = 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1

Example 2:

Input: n = 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1

Constraints:

• 1 <= n <= 104

## Solutions

• class Solution {
public int clumsy(int N) {
Deque<Integer> s = new ArrayDeque<>();
s.offerLast(N);
int op = 0;
for (int i = N - 1; i > 0; --i) {
if (op == 0) {
s.offerLast(s.pollLast() * i);
} else if (op == 1) {
s.offerLast(s.pollLast() / i);
} else if (op == 2) {
s.offerLast(i);
} else {
s.offerLast(-i);
}
op = (op + 1) % 4;
}
int res = 0;
while (!s.isEmpty()) {
res += s.pollLast();
}
return res;
}
}

• class Solution:
def clumsy(self, N: int) -> int:
op = 0
s = [N]
for i in range(N - 1, 0, -1):
if op == 0:
s.append(s.pop() * i)
elif op == 1:
s.append(int(s.pop() / i))
elif op == 2:
s.append(i)
else:
s.append(-i)
op = (op + 1) % 4
return sum(s)

• class Solution {
public:
int clumsy(int n) {
stack<int> stk;
stk.push(n);
int k = 0;
for (int x = n - 1; x; --x) {
if (k == 0) {
stk.top() *= x;
} else if (k == 1) {
stk.top() /= x;
} else if (k == 2) {
stk.push(x);
} else {
stk.push(-x);
}
k = (k + 1) % 4;
}
int ans = 0;
while (!stk.empty()) {
ans += stk.top();
stk.pop();
}
return ans;
}
};

• func clumsy(n int) (ans int) {
stk := []int{n}
k := 0
for x := n - 1; x > 0; x-- {
switch k {
case 0:
stk[len(stk)-1] *= x
case 1:
stk[len(stk)-1] /= x
case 2:
stk = append(stk, x)
case 3:
stk = append(stk, -x)
}
k = (k + 1) % 4
}
for _, x := range stk {
ans += x
}
return
}

• function clumsy(n: number): number {
const stk: number[] = [n];
let k = 0;
for (let x = n - 1; x; --x) {
if (k === 0) {
stk.push(stk.pop()! * x);
} else if (k === 1) {
stk.push((stk.pop()! / x) | 0);
} else if (k === 2) {
stk.push(x);
} else {
stk.push(-x);
}
k = (k + 1) % 4;
}
return stk.reduce((acc, cur) => acc + cur, 0);
}