JAVA经典算法40题(9)

【程序17】题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
1.程序分析:采取逆向思维的方法,从后往前推断。
Java代码 复制代码 收藏代码
  1. public class Eat {
  2. static int total(int day){
  3. if(day == 10){
  4. return 1;
  5. }else{
  6. return (total(day+1)+1)*2;
  7. }
  8. public static void main(String[] args){
  9. System.out.println(total(1));
  10. }
  11. }
public class Eat {
    static int total(int day){
    if(day == 10){
        return 1;
    }else{
        return (total(day+1)+1)*2;
    }
    public static void main(String[] args){
        System.out.println(total(1));
    }
}
程序18】题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
Java代码 复制代码 收藏代码
  1. import java.util.ArrayList;
  2. public class pingpang {
  3. String a, b, c ;
  4. public static void main(String[] args) {
  5. String[] op = { "x", "y", "z" };
  6. ArrayList arrayList=new ArrayList();
  7. for (int i = 0; i < 3; i++)
  8. for (int j = 0; j < 3; j++)
  9. for (int k = 0; k < 3; k++) {
  10. pingpang a=new pingpang(op[i],op[j],op[k]);
  11. if(!a.a.equals(a.b)&&!a.b.equals(a.c)&&!a.a.equals("x")
  12. &&!a.c.equals("x")&&!a.c.equals("z")){
  13. arrayList.add(a);
  14. }
  15. }
  16. for(Object a:arrayList){
  17. System.out.println(a);
  18. }
  19. }
  20. public pingpang(String a, String b, String c) {
  21. super();
  22. this.a = a;
  23. this.b = b;
  24. this.c = c;
  25. }
  26. public String toString() {
  27. return "a的对手是"+a+","+"b的对手是"+b+","+"c的对手是"+c+"\n";
  28. }
  29. }  

你可能感兴趣的:(java,的,桃子)