#1006
Medium Algorithms Clumsy factorial
Math Stack Simulation
61.1% acceptance
Feb 25, 2026
440
366
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn clumsy(n: i32) -> i32 {
let mut stack: Vec<i32> = Vec::new();
let mut val = n;
let mut op = 0; // 0=*, 1=/, 2=+, 3=-
stack.push(val);
val -= 1;
while val > 0 {
match op % 4 {
0 => { let t = stack.pop().unwrap(); stack.push(t * val); }
1 => { let t = stack.pop().unwrap(); stack.push(t / val); }
2 => { stack.push(val); }
_ => { stack.push(-val); }
}
op += 1;
val -= 1;
}
stack.iter().sum()
}
}