欢迎光临散文网 会员登陆 & 注册

Leetcode 1006. Clumsy Factorial

2023-03-01 08:14 作者:您是打尖儿还是住店呢  | 我要投稿

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 = 4Output: 7Explanation: 7 = 4 * 3 / 2 + 1

Example 2:

Input: n = 10Output: 12Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1

 

Constraints:

  • 1 <= n <= 104

class Solution {

   public static int clumsy(int n){

        int ans=0;

        if(n<4){

            return fac(n);

        }

        int k=(n-3)>0?(n-3):0;

        ans=fac(n)+k;

        // System.out.println(ans);

        for (int i = n-4;i>=0; i=i-4) {

            int l=(i-3)>0?(i-3):0;

            ans=ans-fac(i)+l;


        }

        return ans;

    }

    public static int fac(int n){

        if(n==0) return 0;

        if(n==1) return 1;

        if(n==2) return 2;

        if(n==3) return 6;

        if(n==4) return 6;

        return n*(n-1)/(n-2); 

    }

}

写个fac的函数,然后依次遍历即可。

Runtime: 2 ms, faster than 70.12% of Java online submissions for Clumsy Factorial.

Memory Usage: 39.4 MB, less than 76.10% of Java online submissions for Clumsy Factorial.


Leetcode 1006. Clumsy Factorial的评论 (共 条)

分享到微博请遵守国家法律