LeetCode.1006 笨阶乘

本文介绍了LeetCode题目1006的解决方案,通过栈实现的算法思路,并附有数学公式推导,适用于理解递归问题的替代方法。

原题

https://leetcode-cn.com/problems/clumsy-factorial/
在这里插入图片描述

思路

1. 用栈,这是最直接的思路
2. 数学公式推导


题解

package com.leetcode.code;

import java.util.Stack;

/**
 * @Description:
 * @ClassName: Code1006
 * @Author: ZK
 * @Date: 2021/4/1 22:53
 * @Version: 1.0
 */
public class Code1006 {

    public static void main(String[] args) {
        int N = 10;
        System.out.println(clumsy(N));
    }

//    用栈,最直接的思路与方法
    public static int clumsy(int N) {
        int res = 0;
        Stack<Integer> stack = new Stack<>();
//        第一个数字先入栈
        stack.push(N);

        for (int i = 1; i < N; i++) {
//            得到第2,3,4...个数字
            int cur = N - i;
//            如果是第2个数字,相乘
            if (i % 4 == 1) {
                stack.push(stack.pop() * cur);
//                如果是第3个数字,相除
            } else if (i % 4 == 2) {
                stack.push(stack.pop() / cur);
//                如果是第4个数字,入栈
            } else if (i % 4 == 3) {
                stack.push(cur);
//                如果是第5个数字,相反数入栈
            } else if (i % 4 == 0) {
                stack.push(-cur);
            }
        }

        while (!stack.isEmpty()) {
            res += stack.pop();
        }

        return res;
    }

//    数学公式推导
//    如下是大佬的推导过程
//    https://leetcode-cn.com/problems/clumsy-factorial/solution/gong-shi-tui-dao-ji-suan-ji-bai-liao-100-xkbv/
    public static int clumsy1(int N) {
        if (N == 1 || N == 2) {
            return N;
        }
        if (N == 3) {
            return 6;
        }
        if (N == 4) {
            return 7;
        }
//        以上是特殊情况,如下是数学公式推导
        if (N % 4 == 0) {
            return N + 1;
        }else if (N % 4 == 1 || N % 4 == 2) {
            return N + 2;
        } else {
            return N -1;
        }
    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值