JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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

Example 2:

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

Code

class Solution {
    public int clumsy(int n) {
        if(n == 1) return 1;
        int res = 0;
        int curr = 1;
        int desc = n;

        for(int i = 0; i < n; i++) {
            if(i % 4 == 0) {
                if(i != 0) {
                    curr = -desc;
                } else {
                    curr = desc;
                }
            } else if (i % 4 == 1) {
                curr *= desc;
            } else if (i % 4 == 2) {
                curr /= desc;
            } else if (i % 4 == 3) {
                curr += desc;
                res += curr;
                curr = 1;
            }

            desc--;
        }

        if(curr != 1) res += curr;

        return res;
    }
}
class Solution {
    public int clumsy(int n) {
        if(n <= 2) return n;

        if(n <= 4) return n + 3;

        int magic = (n - 4) % 4;
        if(magic == 0) {
            return n + 1;
        } else if (magic <= 2){
            return n + 2;
        } else {
            return n - 1;
        }
    }
}