100根香蕉,猴子要背回50米远的家,一次最多只能背50根香蕉,但猴子每走1米后就要吃1根香蕉,问猴子最多可以背多少根香蕉回家?
用java代码如何实现?
package com.li;
public class Test {
//总的香蕉数
private static int count=100;
//每次搬运的最大香蕉数和回家的步数
private static int halfcount=count/2;
//第一次搬运走的步数设置为firstsetp那么走到此地点,剩余的香蕉数为
//count-firstsetp*3,这 个步数的取值设置为使剩余的香蕉数小于或等于halfcount,此时可以搬这剩下的直接回家了
private static int firstsetp=0;
//count-firstsetp*3 剩余的香蕉数也可能稍稍大于halfcount因为多出一两个可能直接放弃不要了
private static int firstsetp_low=0;
public static void main(String[] args) {
getSteps();
getbrana(firstsetp);
getbrana(firstsetp_low);
}
public static void getSteps(){
for(int i=1;i<halfcount/2;i++){
if(i*3>=halfcount){
firstsetp=i;
firstsetp_low=firstsetp-1;
// System.out.println(firstsetp);
break;
}
}
}
public static void getbrana(int setps){
//走到第一站时剩下的香蕉数
int leavecount=count-setps*3;
System.out.print("第一次走: "+setps+" 步,搬运所有的香蕉到第一站后剩余的总香蕉数为:"+leavecount);
//由于每次只能搬halfcount个香蕉,如果走到第一站之后,剩下的香蕉数稍稍大于halfcount那么,稍大于的只能丢弃
if(leavecount>halfcount){
System.out.print(" 丢弃的香蕉数为: "+(leavecount-halfcount));
leavecount=halfcount;
}
//回家的总步数减去已走的步数,为剩下的总步数
int leavesteps=halfcount-setps;
//save为回到家剩余的香蕉数
int save=leavecount-leavesteps;
System.out.println(" 剩余的步数为: "+leavesteps+" 到家剩余的香蕉数为: "+save);
}
}