去商店买苹果,商店只提供两种类型的袋子,只能装下6个苹果的袋子和只能装下8个苹果的袋子。买的苹果,必须用袋子装满,如果装不满,则不买。 给定一个正整数,返回至少使用多少个袋子。
public class Code_AppleMinBags {public static int minBags(int apple){if(apple < 0){return -1;}int maxE = apple/8;int e8=0;int e6=0;boolean isFind = false;for (int i = maxE; i >= 0; i--) {e8 = i * 8;e6 = (apple-e8)/6;if((apple-e8)%6 == 0){e8 = i;isFind = true;break;}}return isFind ? e8+e6 : -1;}public static int minBagAwesome(int apple){if((apple & 1) == 1){ // 如果为奇数,返回-1return -1;}if(apple < 18){return apple == 0 ? 0 : (apple == 6 || apple == 8) ? 1 : (apple == 12 || apple == 14 || apple == 16) ? 2 : -1;}return (apple-18)/8 + 3;}public static void main(String[] args) {for (int apple = 1; apple < 200; apple++) {int a1 = minBagAwesome(apple);int a2 = minBags(apple);if (a1 != a2) {System.out.println(apple + " : " + minBags(apple));}System.out.println(apple +": "+a1 + " = " + a2);}System.out.println("end...");//System.out.println(minBags(100));}
}