蓝桥杯备考随手记: practise04

问题描述:

小明被不明势力劫持。后莫名其妙被扔到 X 星站再无问津。小明得知每天都有飞船飞往地球,但需要 1 元的船票,而他却身无分文。他决定在 X 星站打工。好心的老板答应包食宿,第 1 天给他 1 元钱。并且,以后的每一天都比前一天多 2 元钱,直到他有足够的钱买票。

请计算一下,小明在第几天就能凑够 108 元,返回地球。

思路分析:

  1. 每天的工资递增2元,第一天工资为1元,第二天工资为3元,第三天工资为5元,依此类推。
  2. 统计每天的工资总和,直到总和大于等于108元为止。
  3. 输出达到108元时的天数。

代码实现:

循环:

public class Main {
    public static void main(String[] args) {
        int currentDay = 1; // 当前天数
        int currentDayMoney = 1; // 当天赚的钱
        int totalMoney = 0; // 累计赚的钱

        // 循环直到凑够108元
        while (totalMoney <= 108) {
            currentDayMoney = currentDayMoney + 2; // 每天多赚2元
            totalMoney += currentDayMoney; // 累计赚的钱
            currentDay++; // 天数加1
        }

        System.out.println("小明在第" + currentDay + "天就能凑够108元,返回地球");
    }
}

递归: 

public class Main {
    public static void main(String[] args) {
        int targetMoney = 108;
        
        int days = calculateDaysToBuyTicket(1, 1, 0, targetMoney);

        System.out.println("小明在第" + days + "天就能凑够108元,返回地球");
    }

    public static int calculateDaysToBuyTicket(int currentDay, int currentDayMoney, int totalMoney, int targetMoney) {
        totalMoney += currentDayMoney;
        
        if (totalMoney >= targetMoney) {
            return currentDay;
        } else {
            return calculateDaysToBuyTicket(currentDay + 1, currentDayMoney + 2, totalMoney, targetMoney);
        }
    }
}
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值