最近,亲人给我出了一道题:
啤酒
- 2元1瓶
- 4个瓶盖换1瓶
- 2个空瓶换1瓶
问:
- 10元可以喝几瓶
作为习惯了和机器打交道的狮,还是让机器告诉我答案吧:
var bottle = 0
var cap = 0
var numberBeer = 0
var surplusCap = 0
var surplusBottle = 0
func numberOfBottle(cap:Int, emptyBottle:Int) -> Int {
bottle = bottle + cap/4 + emptyBottle/2
surplusCap = cap%4
surplusBottle = emptyBottle%2
numberOfCapAndBottle(cap/4 + emptyBottle/2)
return bottle
}
func numberOfCapAndBottle(beer:Int) {
surplusCap += beer
surplusBottle += beer
}
func numberOfBeer(beerNumber: Int) -> Int {
bottle = beerNumber
surplusCap = beerNumber
surplusBottle = beerNumber
while surplusBottle >= 2 || surplusCap >= 4 {
numberBeer = numberOfBottle(surplusCap, emptyBottle: surplusBottle)
}
return numberBeer
}
// 10元首先可以买5瓶
numberOfBeer(5) // 15
print(surplusCap) // 3
print(surplusBottle) // 1
你算对了吗?
网友评论