[LeetCode] Clumsy Factorial

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 <= 10000
-2^31 <= answer <= 2^31 - 1  (The answer is guaranteed to fit within a 32-bit integer.)

解题思路

此题的关键在于分组,我们可以以4个元素为一组,这4个元素以*/+连接起来,然后每组元素以-连接起来。最后再把余下的几个元素以-连接起来。

实现代码

//Runtime: 1 ms, faster than 79.30% of Java online submissions for Clumsy Factorial.
//Memory Usage: 31.8 MB, less than 100.00% of Java online submissions for Clumsy Factorial.
class Solution {
    private static final int[] restSum = {0, 1, 2, 6};
    public int clumsy(int N) {
        if (N < 4) {
            return restSum[N];
        }

        int sum = N * (N - 1) / (N - 2) + (N - 3);
        N -= 4;
        while (N >= 4) {
            sum = sum - N * (N - 1) / (N - 2) + (N - 3);
            N -= 4;
        }

        return sum - restSum[N];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容