题解 | #汽水瓶#递归问题
汽水瓶
https://www.nowcoder.com/practice/fe298c55694f4ed39e256170ff2c205f
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int btl = in.nextInt();
if(btl != 0)
System.out.println(process(btl));
}
}
// 返回初始给btl个瓶盖,最多可喝到的汽水数
// process 3 = 3 + 1
static int process(int btl){
int ans = 0;
// 0 ,1瓶直接喝完
if(btl < 2){
return 0;
}
// 2瓶,可借了再还,所以能白嫖一瓶
if(btl == 2){
return 1;
}
if(btl == 3)
return 1;
else{
// 空瓶中3的数量
int nOfThree = btl / 3;
ans += nOfThree;
//剩下的空瓶有 ans + btl - nOfThree*3个
return ans + process(ans + btl - nOfThree*3);
}
}
}
网易游戏公司福利 595人发布