JAVA经典算法50题(6)
时间:2026-01-19
时间:2026-01-19
个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
1.程序分析:采取逆向思维的方法,从后往前推断。
public class Demo17 {
public static void main(String[] args) {
int sum = 1;
for (int i = 0; i < 9; i++) {
sum = (sum + 1) * 2;
}
System.out.println("第一天共摘"+sum);
}
}
【程序18】 题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
public class Demo18 {
static char[] m = { 'a', 'b', 'c' };
static char[] n = { 'x', 'y', 'z' };
public static void main(String[] args) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < n.length; j++) {
if (m[i] == 'a' && n[j] == 'x') {
continue;
} else if (m[i] == 'a' && n[j] == 'y') {
continue;
} else if ((m[i] == 'c' && n[j] == 'x')
|| (m[i] == 'c' && n[j] == 'z')) {
continue;
} else if ((m[i] == 'b' && n[j] == 'z')
|| (m[i] == 'b' && n[j] == 'y')) {
continue;
} else
System.out.println(m[i] + " vs " + n[j]);
}
}
}
}
或
public class Demo18 {
public String a, b, c;
public Demo18(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
public static void main(String[] args) {
Demo18 arr_a = new Demo18("a", "b", "c");
String[] b = { "x", "y", "z" };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
Demo18 arr_b = new Demo18(b[i], b[j], b[k]);
if (!arr_b.a.equals(arr_b.b) & !arr_b.b.equals(arr_b.c)
& !arr_b.c.equals(arr_b.a) & !arr_b.a.equals("x")
& !arr_b.c.equals("x") & !arr_b.c.equals("z")) {
System.out.println(arr_a.a + "--" + arr_b.a);
System.out.println(arr_a.b + "--" + arr_b.b);
System.out.println(arr_a.c + "--" + arr_b.c);
}
}
}
}
}
}
【程序19】 题目:打印出如下图案(菱形)
1.程序分析:先把图形分成两部分来看待,前四行一个规律,后三行一个规律,利用双重for循环,第一层控制行,第二层控制列。
三角形:
*
***
******
********
******
***
*
public class Demo19 {
public static void main(String[] args) {
int i=0;
int j=0;
for ( i = 1; i <= 4; i++) {
for ( j = 1; j <= 2 * i - 1; j++)
System.out.print("*");
System.out.println();
}
for ( i = 3; i >= 1; i--) {
for ( j = 1; j <= 2 * i - 1; j++)
System.out.print("*");
System.out.println
();
}
}
}
菱形:
*
***
*****
*******
*****
***
*
public class Demo19 {
public static void main(String[] args) {
int i = 0;
int j