[Java] 纯文本查看 复制代码
/*Test10--28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,
* 够28人喝?假如是50人,又需要买多少瓶可乐?
* 分析:递归求和
* f(1)=1.....1;
* f(2)=2.....2;
* f(3)=3.....3;
* f(4)=3.....1;
* f(5)=4.....2;
* f(6)=5.....3;
* f(7)=5.....1;
* @autor李杨
*/
public class Test10 {
public static void main(String[] args) {
int people = 28;
int out = count(people);
System.out.println(out);
}
private static int count(int people) {
int num = 0;
if (people >= 1 && people <= 3) {
return people;
} else {
num += (count(people - 3) + 2);
}
return num;
}
}
[Java] 纯文本查看 复制代码
import java.util.Scanner;
class ByCocl{
public static void main(String[] args) {
System.out.println("请输入一共有几个人");
Scanner sc = new Scanner(System.in);
int allPeople = sc.nextInt() ;
int real = 0 ;//实际需要购买的可乐数量
int all = 0 ;// 按照买三赠一总共买多少可乐
for (int i = 1 ; all <= allPeople ; i++){
all = 3 * i + i ;
real =3 * i ;
}
int temp1 = all - allPeople ;
//如果实际买的加上赠品的数量比人数还多,应该用real减去两者之间的差再加上1
if(temp1 > 0){
real = real - temp1 +1 ;
}
System.out.println("实际一共需要买"+real+"瓶可乐");
}
}