DDSA Solutions

1006. Clumsy Factorial

Time: O(1)
Space: O(1)
Advertisement

Intuition

Simulate clumsy factorial with operations *, /, +, - cycling. Use stack to handle operator precedence.

Algorithm

  1. 1Stack-based evaluation. Current op cycles through *,/,+,- for indices 0,1,2,3,...
  2. 2For *: multiply top. For /: divide top. For +: push positive. For -: push negative.
  3. 3Sum the stack.

Common Pitfalls

  • Integer division truncates toward zero in C#. First operation starts with *.
1006.cs
C#
// Approach: Closed-form formula based on n mod 4; compute offset pattern directly without simulation.
// Time: O(1) Space: O(1)

public class Solution
{
    public int Clumsy(int n)
    {
        if (n == 1)
            return 1;
        if (n == 2)
            return 2;
        if (n == 3)
            return 6;
        if (n == 4)
            return 7;
        if (n % 4 == 1)
            return n + 2;
        if (n % 4 == 2)
            return n + 2;
        if (n % 4 == 3)
            return n - 1;
        return n + 1;
    }
}
Advertisement
Was this solution helpful?