美文网首页程序员代码面试
[LeetCode] Clumsy Factorial

[LeetCode] Clumsy Factorial

作者: 埋没随百草 | 来源:发表于2019-04-21 13:36 被阅读0次

    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];
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode] Clumsy Factorial

        本文链接:https://www.haomeiwen.com/subject/lbadgqtx.html