#Java编程题-百钱百鸡
问题:
百钱百鸡问题。用100钱买100只鸡,公鸡一只五钱,母鸡一只三钱,雏鸡三只一钱,编程计算共有几种买法(要求每种鸡至少要买1只)。 |
自己的实现,没有什么数据结构,算法,求大神指点!!
package com.ckhuang.maven.confused; /** * 程序功能:百钱百鸡问题(一百元买一百只鸡)。<br/> * 用100钱买100只鸡,公鸡一只五钱,母鸡一只三钱,雏鸡三只一钱,<br/> * 编程计算共有几种买法(要求每种鸡至少要买1只)。 * * @author ck.huang * */ public class HundredChicken { public static final int ROOSTER_PRICE = 5; public static final int HEN_PRICE = 3; public static final int BIDDY_PRICE = 1; public static final int BIDDY_NUM_PER_YUAN = 3; /** * @param args */ public static void main(String[] args) { int totalMoney = 100; int waysCount = 0; int maxRooster = (totalMoney - HEN_PRICE - BIDDY_PRICE) / ROOSTER_PRICE; int maxHen = 0;// 最大购买母鸡数 int biddyNum = 0;// 购买雏鸡数量 for (int i = 1; i <= maxRooster; i++) { maxHen = (totalMoney - (ROOSTER_PRICE * i) - BIDDY_PRICE) / HEN_PRICE; for (int j = 1; j <= maxHen; j++) { biddyNum = (totalMoney - (ROOSTER_PRICE * i) - HEN_PRICE * j) / BIDDY_PRICE; if (i + j + (biddyNum * BIDDY_NUM_PER_YUAN) == 100) { System.out.println("购买公鸡:" + i + "只(" + (ROOSTER_PRICE * i) + "),购买母鸡:" + j + "只(" + (HEN_PRICE * j) + "钱),购买雏鸡:" + (biddyNum * BIDDY_NUM_PER_YUAN) + "只(" + biddyNum + "钱)"); waysCount++; } } } System.out.println("共有:" + waysCount + "种方式购买!"); } }
结果:
购买公鸡:4只(20),购买母鸡:18只(54钱),购买雏鸡:78只(26钱) |