【问题描述】
话说大诗人李白,一生好饮。幸好他从不开车。
一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:
无事街上走,提壶去打酒。
逢店加一倍,遇花喝一斗。
这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。
请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。
【问题分析】
【程序代码】
1 public class 蓝桥杯_第五届_李白打酒 2 { 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 6 int count=0;//方案个数计数器 7 8 //对所有可能方案进行穷举,0代表店,1代表花 9 for(int i=Integer.parseInt("00000111111111", 2);i<=Integer.parseInt("11111111100000", 2);i++) 10 { 11 //将整数转换为二进制字符串,由于最后肯定是花,所以最后一位连接一个1 12 String str=Integer.toBinaryString(i)+"1"; 13 14 //如果字符串不足15位,前补0 15 int t=15-str.length(); 16 for(int j=0;j<t;j++) 17 { 18 str="0"+str; 19 } 20 //str=String.format("%015d",Long.parseLong(str)); 21 22 //测试字符串中是否含有10个1(即10个花) 23 //符合这个条件才有可能是其中一个解 24 if(ten_one(str)) 25 { 26 int jh=2;//酒壶里开始有2斗酒 27 28 //对当前字符串序列按"遇店(0)加一倍,遇花(1)喝一斗" 29 //推算酒壶最后的剩余酒量 30 for(int j=0;j<str.length();j++) 31 { 32 if(str.charAt(j)==‘1‘) 33 { 34 jh-=1; 35 } 36 else 37 { 38 jh*=2; 39 } 40 } 41 42 //如果最后酒壶中没酒, 43 //就是一种可能的方案,计数器加1 44 if(jh==0) 45 { 46 count++; 47 //System.out.println(str); 48 } 49 } 50 } 51 System.out.println(count); 52 } 53 54 //判断字符串中是否含有10个1 55 //是,返回true,否,返回false 56 private static boolean ten_one(String str) { 57 58 int cc=0; 59 for(int i=0;i<str.length();i++) 60 { 61 if(str.charAt(i)==‘1‘) 62 cc++; 63 } 64 if(cc==10) 65 return true; 66 return false; 67 } 68 }
原文:http://www.cnblogs.com/yzzdzy/p/4369643.html