题解 | #百钱买百鸡问题#
百钱买百鸡问题
https://www.nowcoder.com/practice/74c493f094304ea2bda37d0dc40dc85b
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int num = in.nextInt();
// 鸡翁个数
int count1 = 0;
// 鸡母个数
int count2 = 0;
// 鸡雏个数
int count3 = 0;
for (count1 = 0; count1 < 20; count1++) {
for (count2 = 0; count2 <= 33; count2++) {
count3 = 100 - count1 -count2;
if(5*count1 + 3*count2 + count3/3 == 100 && count3%3 == 0)
System.out.println(count1+ " " + count2 + " " + count3);
}
}
}
}
}
解题思路:
- 首先,鸡翁1只五钱,鸡母1只三钱,鸡雏3只1钱,得出100最多买20只鸡翁,33只鸡母
- 外层循环遍历鸡翁数量,内层循环遍历鸡母数量,根据条件计算鸡雏数量
- 再根据条件判断是否满足100钱买一百鸡,满足则输出。

