当前位置:网站首页>[number theory] leetcode1006 Clumsy Factorial

[number theory] leetcode1006 Clumsy Factorial

2022-06-21 15:44:00 Twilight_ years

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( Round down ) such that 10 * 9 / 8 = 90 / 8 = 11.

Given an integer n, return the clumsy factorial of n.

The question : seek clumsy factorial ,*/+- The four symbols alternate .

because / It's rounding down , So you can separate constants .

 

 

 

The rest cannot be done 4 One component pair 「 elimination 」 The situation needs to be classified and discussed . because 「 Stupid factorials 」 according to 「 ride 」「 except 」「 Add 」「 reduce 」 The order of the loop defines the operation , take n According to the right 4  Discussion on remainder classification of modulo .

(1)n%4==0

(2)n%4==1 

(3)n%4==2

 

(4)n%4==3

 

  • When  n≤4  when , Can be calculated separately 「 Stupid factorials 」;

  • When n>4  when , According to  n  Yes  4  Take the remainder of the module to discuss the classification .

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

原网站

版权声明
本文为[Twilight_ years]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211243137786.html