LeetCode1006(2021.4.1)

LC1006. 笨阶乘

class Solution {
    //模拟
    public int clumsy(int N) {
        Deque<Integer> stack = new LinkedList<Integer>();
        stack.push(N--);
        int op = 0;
        while (N > 0) {
            if (op % 4 == 0) {
                stack.push(stack.pop() * N);
            }
            else if (op % 4 == 1) {
                stack.push(stack.pop() / N);
            }
            else if (op % 4 == 2) {
                stack.push(N);
            }
            else {
                stack.push(-N);
            }
            op++;
            N--;
        }
        int res = 0;
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }

    //数学推导
    public int clumsy(int N) {
        if (N <= 2) {
            return N;
        }
        else if (N == 3) {
            return 6;
        }
        else if (N == 4) {
            return 7;
        }
        if (N % 4 == 0) {
            return N + 1;
        }
        else if (N % 4 <= 2) {
            return N + 2;
        }
        else {
            return N - 1;
        }
    }
}

留下评论