买苹果(找规律)

题目描述

小易去附近的商店买苹果,奸诈的商贩使用了捆绑交易,只提供6个每袋和8个每袋的包装(包装不可拆分)。 可是小易现在只想购买恰好n个苹果,小易想购买尽量少的袋数方便携带。如果不能购买恰好n个苹果,小易将不会购买。

输入描述:

输入一个整数n,表示小易想购买n(1 ≤ n ≤ 100)个苹果

输出描述:

输出一个整数表示最少需要购买的袋数,如果不能买恰好n个苹果则输出-1
示例1

输入

20

输出

3

 1 import java.util.Scanner;
 2 
 3 /**
 4  * 
 5  * 买苹果 :
 6  *         要袋数少就要尽可能的买 8个 
 7  *          4袋6个等于3袋8个可以转化 --- 24个苹果
 8  *          剩下的就是在 (0、1、2、3)个6 和 (0、1、2)个8之间找
 9  * @author Dell
10  *
11  */
12 public class Main {
13 static public int f(int n) {
14     int x = 3*(n/24);//加括号
15     int mod = n%24;
16     for (int i = 0; i < 4; i++) {
17         for (int j = 0; j < 3; j++) {
18             if (i*6+j*8==mod) {
19                 x = x+i+j;
20                 return x;
21             }
22         }
23     }
24     return -1;
25 }
26 public static void main(String[] args) {
27 Scanner sc = new Scanner(System.in);
28 int n = sc.nextInt();
29 int x= f(n);
30 System.out.println(x);
31 }
32     
33 }
原文地址:https://www.cnblogs.com/the-wang/p/8981204.html