[LeetCode] Clumsy Factorial

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.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int clumsy(int n, int sign = 1) {
if(n == 3) return sign * 3 * 2 / 1;
if(n == 2) return sign * 2 * 1;
if(n == 1) return sign * 1;
if(n == 0) return 0;
return sign * n * (n - 1) / (n - 2) + (n - 3) + clumsy(n - 4, -1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/06/PS/LeetCode/clumsy-factorial/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.