Skip to content

1048. Clumsy Factorial

Difficulty: Medium

LeetCode Problem View on GitHub


1048. Clumsy Factorial

Medium


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

Solution

class Solution {
    public int clumsy(int n) {
        char operation[] = {'*', '/', '+', '-'};
        int current_operation = 0;
        ArrayList<Integer> res = new ArrayList<>();
        int current_res = n;
        for (int i = n - 1; i >= 1; i--) {
            if (operation[current_operation] == '*') current_res *= i;
            else if (operation[current_operation] == '/') current_res /= i;
            else if (operation[current_operation] == '+') {
                if (res.size() > 0) current_res -= i;
                else current_res += i;
            }
            else {
                res.add(current_res);
                current_res = i;
            }
            current_operation++;
            current_operation %= 4;
        }
        res.add(current_res);
        if (res.size() == 0) return current_res;
        int ans = res.get(0);
        for (int i = 1; i < res.size(); i++) ans -= res.get(i);
        return ans;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here