太可惜了 思路如此简单的购买水果问题
小红去买水果,袋装的,6个一袋,或是8个一袋,不能拆开散卖,要么不买,要么恰好买了n个水果,
且用的袋子数量最少。 n范围:(1<=n<=100);不买则返回-1;买的话,则返回恰好所需要买的水果
应盛放的袋子的最少数量。
such as :输入 20;返回 3. because 20 = 8 + 6 + 6.
记得导包!!!(疏忽大意)
import java.util.Scanner;
public class Main {
public static int test(int n) {
int x = n / 8;
int y = n % 8;
if (y == 0) {
return x;
} else {
for (int i = 1; i <= x; i++) {
if ((y + i * 8) % 6 == 0) {
return (x - i) + (y + i * 8) / 6;
}
}
return -1;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int ans = test(n);
System.out.println(ans);
}
}
运行结果如下:
20=8+6+6
28=8+8+6+6
36=8+8+8+6+6
37=?
5=?