题解 | 汽水瓶
汽水瓶
https://www.nowcoder.com/practice/fe298c55694f4ed39e256170ff2c205f
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for {
if scanner.Scan() {
resCount := 0
emptyCountStr := scanner.Text()
emptyCountInt, _ := strconv.Atoi(emptyCountStr)
if emptyCountInt == 0 {
break
}
if emptyCountInt < 0 {
resCount = 0
} else if emptyCountInt == 2 {
resCount = 1
} else {
for {
canDrink := emptyCountInt / 3
resCount += canDrink
emptyCountRelease := emptyCountInt % 3
emptyCountInt = canDrink + emptyCountRelease
if emptyCountInt <= 1 {
break
} else if emptyCountInt == 2 {
resCount++
break
}
}
}
fmt.Printf("%d\n", resCount)
}
}
}
解题思路:当剩余的汽水瓶是1的时候,无法再通过借来兑换,当剩余的为2时,可以通过借空瓶子来集齐3个空瓶,再兑换一瓶喝掉然后归还。因此循环时只需要注意剩余的汽水瓶到达临界点时的处理条件即可
查看6道真题和解析