当前位置:网站首页>【数论】leetcode1006. Clumsy Factorial

【数论】leetcode1006. Clumsy Factorial

2022-06-21 15:33:00 暮色_年华

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.

题意:求clumsy factorial ,*/+-四个符号交替使用。

因为/是下取整,所以可以分离常数。

 

 

 

剩下不能够成 4个一组成对「消去」的情况需要分类讨论。由于「笨阶乘」按照「乘」「除」「加」「减」循环的顺序定义运算,将 n 按照对 4 取模的余数分类讨论。

(1)n%4==0

(2)n%4==1 

(3)n%4==2

 

(4)n%4==3

 

  • 当 n≤4 时,可以分别单独计算「笨阶乘」;

  • 当n>4 时,可以根据 n 对 4 取模的余数进行分类讨论。

  • class Solution {
        public int clumsy(int n) {
            if(n==1)return 1;
            if(n==2)return 2;
            if(n==3)return 6;
            if(n==4)return 7;
            if(n%4==0)return n+1;
            if(n%4<=2)return n+2;
            return n-1;
    
        }
    }

原网站

版权声明
本文为[暮色_年华]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_52043808/article/details/125385745