1006. Clumsy Factorial #
Problem #
Normally, 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 instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: 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 equals 11. This guarantees the result is an integer.
Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.
Example 1:
Input:4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1
Example 2:
Input:10
Output:12
Explanation:12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
Note:
1 <= N <= 100002^31 <= answer <= 2^31 - 1(The answer is guaranteed to fit within a 32-bit integer.)
Summary #
Usually, 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. Instead, we design a clumsy factorial, clumsy: in the decreasing sequence of integers, we replace the original multiplication operators in sequence with a fixed-order sequence of operators: multiplication (*), division (/), addition (+), and subtraction (-). For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations still use the usual order of arithmetic operations: we perform all multiplication and division steps before any addition or subtraction steps, and process multiplication and division steps from left to right. In addition, the division we use is floor division, so 10 * 9 / 8 equals 11. This guarantees that the result is an integer. Implement the clumsy function defined above: given an integer N, it returns the clumsy factorial of N.
Solution Approach #
- According to the problem statement, since there are no parentheses in this problem, multiplication and division are performed before addition and subtraction. Operations are grouped in sets of 4: first calculate multiplication, then division, then addition, and finally subtraction. Subtraction can also be regarded as addition, just addition with a negative sign.
Code #
package leetcode
func clumsy(N int) int {
res, count, tmp, flag := 0, 1, N, false
for i := N - 1; i > 0; i-- {
count = count % 4
switch count {
case 1:
tmp = tmp * i
case 2:
tmp = tmp / i
case 3:
res = res + tmp
flag = true
tmp = -1
res = res + i
case 0:
flag = false
tmp = tmp * (i)
}
count++
}
if !flag {
res = res + tmp
}
return res
}