“汽水三换一”问题的两种问法及巧妙解答

此题今年我在包括360在内的三家公司的笔试面试中遇到过，总结了此题的两种问法及巧妙解决方案，方便大家应对招聘或者当个智力题开动下思维也好。

public class SanHuanYi {

/**
* @param args
*/
public static void main(String[] args) {

int init_bottle_num = 30;//初始汽水的数量
int person_num = 0;//能供给同学的数量

person_num = getAllBottleNum(init_bottle_num);
System.out.println(person_num);

}
static int getAllBottleNum(int bottle_num){
if(bottle_num <= 0)
return 0;
int all_num = bottle_num;//all_num最终数量
while(bottle_num >= 3){
int temp = bottle_num / 3;
all_num += temp;
bottle_num = temp + bottle_num % 3;
}
all_num += bottle_num == 2 ? 1: 0;//剩两瓶总数量就加1
return all_num;
}

}


public class SanHuanYi {

/**
* @param args
*/
public static void main(String[] args) {

int person_num = 30;//需要供给的人数
int all_bottle_num = getLeastBottle(person_num);
System.out.println(all_bottle_num);

}

static int getLeastBottle(int person_num){

if(person_num <= 0)
return 0;
if(person_num > 0 && person_num < 3)
return person_num;
int sum = 0;
int group_num = person_num / 3;//能够分的组数
int yushu = person_num % 3;//分组完，剩余的人
sum = 3 + (group_num-1) * 2;
if(yushu == 0){
sum--;
}else if(yushu == 1){

}else{
sum++;
}

return sum;
}
}


==================================================================================================

作者：nash_  欢迎转载，与人分享是进步的源泉！

===================================================================================================