使用递归做法,不需要找规律,找规律是投机取巧罢了
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//遍历测试数据
while (sc.hasNext()){
int num = sc.nextInt();
//如果输出0则退出遍历
if(num == 0){
break;
}else {
countCola(num,0);
}
}
}
/*递归函数*/
private static void countCola(int num,int count){
int chuShu = num / 3;
int yuShu = num % 3;
//这么什么好说的,应该都看得懂
count = count + chuShu;
num = chuShu + yuShu;
//如果除数加余数是1,则借不了汽水,因为喝了你也还不了
if(num == 1){
System.out.println(count);
return;
}
//如果余数加除数是2或者3,那么你可以直接换汽水,或者借一瓶汽水,喝完再还
if(num == 2 || num == 3){
count++;
System.out.println(count);
//如果以上情况都不是,接着递归
}else{
countCola(num,count);
}
}
}