问题描述:
小明被不明势力劫持。后莫名其妙被扔到 X 星站再无问津。小明得知每天都有飞船飞往地球,但需要 1 元的船票,而他却身无分文。他决定在 X 星站打工。好心的老板答应包食宿,第 1 天给他 1 元钱。并且,以后的每一天都比前一天多 2 元钱,直到他有足够的钱买票。
请计算一下,小明在第几天就能凑够 108 元,返回地球。
思路分析:
- 每天的工资递增2元,第一天工资为1元,第二天工资为3元,第三天工资为5元,依此类推。
- 统计每天的工资总和,直到总和大于等于108元为止。
- 输出达到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);
}
}
}