前言
使用的是《算法》第四版英文版,主要是习题解答。
书中jar包的导入请戳:算法(第四版)中algs4.jar下载和使用
EXERCISES
1.1.1
1.1.2
1.1.3
import java.util.Scanner;
public class Something {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
if (a == b && a == c)
System.out.println("equal");
else
System.out.println("not equal");
}
}
1.1.4
a. 去掉then
b. a > b用括号括起来
c. true
d. true
1.1.5
import java.util.Scanner;
public class Something {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double x = scanner.nextDouble();
double y = scanner.nextDouble();
if ((x > 0.0 && x < 1.0) && (y > 0.0 && y < 1.0))
System.out.println("true");
else
System.out.println("false");
}
}
1.1.6
1.1.7
1.1.8
1.1.9
import java.util.Scanner;
// 不建议用String,因为对String对象的修改要重新创建一个String对象
// 可以好好查查资料,String、StringBuild和StringBuffer的区别
public class Something {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
StringBuilder sb = new StringBuilder();
while (N > 0) {
int temp = N % 2;
N /= 2;
sb.append(temp);
}
sb.reverse();
System.out.println(sb);
}
}
1.1.10
// 修正如下。主要是未给数组分配内存空间
int[] a = new int[10];
1.1.11
import java.util.Scanner;
public class Something {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt(); // 二维数组的行数
int col = scanner.nextInt(); // 二维数组的列数
boolean[][] res = new boolean[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
res[i][j] = scanner.nextBoolean();
}
}
// ============之间的为二维数组打印
System.out.println("=============");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (res[i][j] == true)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
System.out.println("=============");
}
}
1.1.12
1.1.13
import java.util