JS算法例子
- 换酒瓶算法:初始有n瓶酒,m瓶空瓶子可换一瓶酒,求最多能喝几瓶酒
//返回喝酒的瓶数,参数1初始酒数量,参数2空瓶数量换一瓶酒 function changeBottle(initBottle,numchange){ let total = 0;//喝的瓶数 let empty = 0;//空瓶数 while(initBottle>0){//只要有酒就继续喝 total += initBottle; empty += initBottle; initBottle = 0; let changes = Math.floor(empty/numchange); if(changes>0){ initBottle = changes; empty = empty % numchange; } } console.log(total); }
浙公网安备 33010602011771号