
image.png
請(qǐng)聽(tīng)題:
每瓶啤酒2元,2個(gè)空酒瓶或4個(gè)瓶蓋可換1瓶啤酒。10元最多可喝多少瓶啤酒?
關(guān)于答案:網(wǎng)上有非常多的解答。包括:
- 一步步進(jìn)行推算
- 設(shè)一瓶酒里的酒價(jià)值x,酒瓶?jī)r(jià)值y,瓶蓋價(jià)值z(mì),列等式進(jìn)行計(jì)算
- 跟老板賒賬或者借酒瓶或者瓶蓋計(jì)算
- ...等等
作為一名程序猿,用筆一步步計(jì)算太麻煩了,知道原理,那就寫(xiě)個(gè)遞歸算法計(jì)算一波吧。
注:以下為Swift代碼
var drinkTotal = 5 // 總共喝的啤酒的數(shù)量,初始化為5,即購(gòu)買(mǎi)的5瓶
var leftBottle = 0 // 剩余空瓶的數(shù)量
var leftCover = 0 // 剩余瓶蓋的數(shù)量
func convert(_ bottle: Int, _ cover: Int) -> Int {
if bottle >= 2 || cover >= 4 {
leftBottle = (bottle / 2) + (bottle % 2) + (cover / 4)
leftCover = (cover / 4) + (cover % 4) + (bottle / 2)
return (bottle / 2) + (cover / 4) + convert(leftBottle, leftCover)
}
return 0
}
drinkTotal += convert(5, 5)
print("\n總共喝了\(drinkTotal)瓶啤酒,還剩下\(leftBottle)個(gè)空瓶,\(leftCover)個(gè)空蓋")
這里不多詳細(xì)解釋了。下面的方案比較詳細(xì)易懂
// 啤酒信息類(lèi)
class TurnBeerInfo {
var bottleTotal = 0 // 空瓶的數(shù)量
var coverTotal = 0 // 瓶蓋的數(shù)量
var drinkTotal = 0 // 已喝啤酒的數(shù)量
}
// 購(gòu)買(mǎi)啤酒
func buyBeer(_ money: Int, _ turnBeerInfo: TurnBeerInfo) {
let beerTotal = money / 2
turnBeerInfo.bottleTotal = beerTotal
turnBeerInfo.coverTotal = beerTotal
turnBeerInfo.drinkTotal = beerTotal
}
// 兌換啤酒
func convert(_ turnBeerInfo: TurnBeerInfo, _ i: Int) {
// 用空瓶?jī)稉Q啤酒的數(shù)量
let bottleTurnNum = turnBeerInfo.bottleTotal / 2
// 計(jì)算空瓶?jī)稉Q后的瓶蓋數(shù)量
turnBeerInfo.coverTotal += bottleTurnNum
// 用瓶蓋兌換啤酒的數(shù)量
let coverTurnNum = turnBeerInfo.coverTotal / 4
// 重新計(jì)算瓶蓋兌換后的瓶蓋數(shù)量
turnBeerInfo.coverTotal = turnBeerInfo.coverTotal % 4 + coverTurnNum
// 重新計(jì)算瓶蓋兌換后的空瓶數(shù)量
turnBeerInfo.bottleTotal = turnBeerInfo.bottleTotal % 2 + bottleTurnNum + coverTurnNum
// 計(jì)算總共喝了幾瓶
turnBeerInfo.drinkTotal = turnBeerInfo.drinkTotal + coverTurnNum + bottleTurnNum
print("這是第\(i)次兌換,目前已喝了\(turnBeerInfo.drinkTotal)瓶啤酒,還剩下\(turnBeerInfo.bottleTotal)個(gè)空瓶,\(turnBeerInfo.coverTotal)個(gè)瓶蓋")
// 滿(mǎn)足條件,繼續(xù)計(jì)算
if turnBeerInfo.bottleTotal >= 2 || turnBeerInfo.coverTotal >= 4 {
let j = i + 1
convert(turnBeerInfo, j)
}
}
let turnBeerInfo = TurnBeerInfo()
let totalMoney = 10
buyBeer(totalMoney, turnBeerInfo)
convert(turnBeerInfo, 1)
print("\n總共喝了\(turnBeerInfo.drinkTotal)瓶啤酒,還剩下\(turnBeerInfo.bottleTotal)個(gè)空瓶,\(turnBeerInfo.coverTotal)個(gè)空蓋")

image.png