- package basetest;
- /*
- * 1:矿泉水1元钱1瓶,每2个空瓶换一瓶矿泉水,现有20元钱,请问可以买多少瓶矿泉水?
- */
- /* mon = 20;
- wat = 20;
- bot = 20;
- wat = 10;
- bot = 10;
- wat = 5;<
- bot = 5;
- wat = 2;//余1
- bot = 2;
- wat = 1;
- bot = 2;
- wat = 1;
- bot = 1;*/
- public class bottle {
- public static void main(String[] args){
- System.out.println(water(20));
- }
- public static int water(int money){
- int bottle = 0,water = 0;
- water = money;
- bottle = water;
- //当只剩一个瓶子的时候,买不了水了,另想办法吧
- while(bottle>1){
- //瓶子是2的整数倍时,刚好能买瓶子一半的水
- while(!(bottle%2==1)&&bottle>1){
- bottle = bottle/2;
- water += bottle;
- }
- //瓶子不是2的整数倍时,买完水剩下一个瓶子,再加回来
- while(bottle%2==1&&bottle>1){
- bottle = bottle/2;
- water += bottle;
- bottle += 1;
- }
- }
- water +=1;//最后再借个瓶子买瓶水,把瓶子还回去,完美了
- return water;
- }
- }
复制代码看到这个题,自己写了个小程序,分享下,看看方法有问题不?
|