问题描述:
一个小猴子边上有100根香蕉,它要走过50米才能到家,每次它最多搬50根香蕉。它每走1米就要吃掉一根,请问它最多能把多少根香蕉搬到家里呢?
提示:他可以把香蕉放下往返的走,但是必须保证它每走一米都能有香蕉吃。也可以走到n米时,放下一些香蕉,拿着n根香蕉走回去重新搬50根。
程序实现:
接口:
-
public interface MonkeysMoveBananas {
-
-
-
-
-
-
-
-
-
-
-
-
int Move(int num, int maxNum, int distance, int eatNum);
-
实现类:
-
-
-
-
-
public class MonkeysMoveBananasImpl implements MonkeysMoveBananas {
-
-
-
-
-
-
-
-
-
-
-
-
-
public int Move(int num, int maxNum, int distance, int eatNum) {
-
-
-
-
-
-
int CurrentNumberS = num;
-
-
-
-
-
-
while(location < distance && CurrentNumberS > eatNum) {
-
System.out.println("当前所在位置" + location + "有" + CurrentNumberS + "个香蕉");
-
-
-
-
-
if(CurrentNumberS > maxNum) {
-
MoveOnePosition(location, location+1, maxNum, eatNum);
-
CurrentNumberS -= maxNum;
-
CurrentNumberE += maxNum -eatNum;
-
-
MoveOnePosition(location, location+1, CurrentNumberS, eatNum);
-
CurrentNumberE += CurrentNumberS - eatNum;
-
-
-
-
-
if(CurrentNumberS >= eatNum * 2) {
-
MoveOnePosition(location+1, location, -1, eatNum);
-
CurrentNumberE -= eatNum;
-
-
-
-
-
-
CurrentNumberS = CurrentNumberE;
-
-
-
-
-
System.out.println("剩余" + CurrentNumberS + "个");
-
-
-
-
-
-
-
-
-
-
-
private void MoveOnePosition(int from, int to, int number, int eatNum) {
-
-
System.out.println("从 " + from + " 位置搬 "+ number + " 个到 " + to + " 位置, 消耗" + eatNum + "个");
-
-
System.out.println("从 " + from + " 位置回到 " + to + " 位置, 消耗 " + eatNum + "个");
-
-
-
测试类:
-
public class MonkeysMoveBananasTest {
-
-
private static MonkeysMoveBananas monkeysMoveBananas = null;
-
-
-
public static void setUpBeforeClass() throws Exception {
-
monkeysMoveBananas = new MonkeysMoveBananasImpl();
-
-
-
-
-
int k = monkeysMoveBananas.Move(100, 50, 50, 1);
-
-
-
k = monkeysMoveBananas.Move(1000, 50, 50, 2);
-
-
-
-