Algorithm


Problem Name: 1006. Clumsy Factorial

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

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const clumsy = function(N) {
  const ops = ["*", "/", "+", "-"];
  const arr = [];
  arr.push(N);
  for (let i = N - 1, idx = 0; i > 0; i--, idx++) {
    let op = ops[idx % 4];
    let arrIdx = arr.length - 1  <  0 ? 0 : arr.length - 1;
    switch (op) {
      case "*":
        arr[arrIdx] *= i;
        break;
      case "/":
        arr[arrIdx] = Math.floor(arr[arrIdx] / i);
        break;
      case "+":
        arr[0] += i;
        break;
      case "-":
        arr.push(i);
        break;
    }
  }

  let res = arr[0];
  for (let i = 1; i  <  arr.length; i++) {
    res -= arr[i];
  }
  return res;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 4

Output

x
+
cmd
7

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def clumsy(self, N: int) -> int:
        if N <= 2:
            return N
        if N <= 4:
            return N + 3
        if N % 4 == 0:
            return N + 1
        elif N % 4 <= 2:
            return N + 2
        else:
            return N - 1
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 4

Output

x
+
cmd
7
Advertisements

Demonstration


Previous
#1005 Leetcode Maximize Sum Of Array After K Negations Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#1007 Leetcode Minimum Domino Rotations For Equal Row Solution in C, C++, Java, JavaScript, Python, C# Leetcode