经典算法题--换汽水瓶
作者:互联网
“某商店规定:三个空汽水瓶可以换一瓶汽水。小张手上有十个空汽水瓶,她最多可以换多少瓶汽水喝?”答案是5瓶,方法如下:先用9个空瓶子换3瓶汽水,喝掉3瓶满的,喝完以后4个空瓶子,用3个再换一瓶,喝掉这瓶满的,这时候剩2个空瓶子。然后你让老板先借给你一瓶汽水,喝掉这瓶满的,喝完以后用3个空瓶子换一瓶满的还给老板。如果小张手上有n个空汽水瓶,最多可以换多少瓶汽水喝?
Java版
import java.io.BufferedInputStream; import java.util.Scanner; public class Glass { public static void main(String[] args) { Scanner scanner = new Scanner(new BufferedInputStream(System.in)); while (scanner.hasNext()) { int countOriginal = scanner.nextInt(); if (countOriginal == 0) { break; } System.out.println(countGlass(countOriginal)); } } private static int countGlass(int countOriginal) { int count = 0; while (countOriginal >= 3) { int temp = countOriginal / 3; //计算商 count += temp; //兑换的瓶数加上商 int remainder = countOriginal % 3; //计算余数 countOriginal = remainder + temp; //空瓶数 = 余数 + 商 } if (countOriginal == 2) { count += 1; } return count; } }
标签:count,汽水,个空,int,countOriginal,算法,经典,汽水瓶 来源: https://www.cnblogs.com/fcbyoung/p/12562378.html