File tree Expand file tree Collapse file tree
src/main/java/com/fancv/leetCode/mathematics Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .fancv .leetCode .mathematics ;
2+
3+ /**
4+ * @author hamish-wu
5+ */
6+ public class FactorialClumsy {
7+
8+
9+ public static void main (String [] args ) {
10+
11+ System .out .println (clumsy (4 ));
12+ }
13+
14+ /**
15+ * 通常,正整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。例如,factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1。
16+ * <p>
17+ * 相反,我们设计了一个笨阶乘 clumsy:在整数的递减序列中,我们以一个固定顺序的操作符序列来依次替换原有的乘法操作符:乘法(*),除法(/),加法(+)和减法(-)。
18+ * <p>
19+ * 例如,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1。然而,这些运算仍然使用通常的算术运算顺序:我们在任何加、减步骤之前执行所有的乘法和除法步骤,并且按从左到右处理乘法和除法步骤。
20+ * <p>
21+ * 另外,我们使用的除法是地板除法(floor division),所以 10 * 9 / 8 等于 11。这保证结果是一个整数。
22+ * <p>
23+ * 实现上面定义的笨函数:给定一个整数 N,它返回 N 的笨阶乘。
24+ * <p>
25+ *
26+ * 来源:力扣(LeetCode)
27+ * 链接:https://leetcode-cn.com/problems/clumsy-factorial
28+ * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
29+ *
30+ * @param N
31+ * @return
32+ */
33+ public static int clumsy (int N ) {
34+ int result = 0 ;
35+ boolean b = false ;
36+ for (int m = N ; m > 0 ; m = m - 4 ) {
37+ result = result + threeNum (m , b );
38+ b = true ;
39+ }
40+
41+
42+ return result ;
43+ }
44+
45+ /**
46+ * 四个数字一组计算
47+ *
48+ * @param a
49+ * @param b
50+ * @return
51+ */
52+ public static int threeNum (int a , boolean b ) {
53+ int temp = 0 ;
54+ if (a > 3 ) {
55+ temp = a * (a - 1 ) / (a - 2 );
56+ if (b ) {
57+ return (a - 3 ) - temp ;
58+ } else {
59+ return temp + a - 3 ;
60+ }
61+ } else {
62+ if (a == 1 || a == 2 ) {
63+ temp = a ;
64+ } else {
65+ temp = 6 ;
66+ }
67+ }
68+ if (b ) {
69+ temp = -temp ;
70+ }
71+ return temp ;
72+ }
73+ }
You can’t perform that action at this time.
0 commit comments