【微软面试题】
请把一段纸条竖着放在桌子上,然后从纸条的下边向上方对折1次,压出折痕后展开。此时折痕是凹下去的,即折痕突起的方向指向纸条的背面。 如果从纸条的下边向上方连续对折2次,压出折痕后展开,此时有三条折痕,从上到下依次是下折痕、下折痕和上折痕。
给定一个输入参数N,代表纸条都从下边向上方连续对折N次。 请从上到下打印所有折痕的方向。 例如:N=1时,打印: down N=2时,打印: down down up 最终答应 凹 凹 凸
1
2
3
public static List<String> printAllFolds(int N) {
}
测试如下:注意,将你写的解法粘贴入类MainChecker
中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
class FoldChecker {
// 暴力解:生成 N 次折叠后的折痕序列
public static List<String> getStandardFolds(int N) {
if (N <= 0) {
return new ArrayList<>();
}
List<String> lastFolds = new ArrayList<>();
lastFolds.add("凹"); // N=1 时的初始序列
for (int i = 2; i <= N; i++) {
List<String> currentFolds = new ArrayList<>();
int size = lastFolds.size();
// 1. 上一次的序列 (左子树)
for (String fold : lastFolds) {
currentFolds.add(fold);
}
// 2. 当前折叠的折痕 (根节点) - 总是“凹”
currentFolds.add("凹");
// 3. 上一次序列的逆序且凹凸性取反 (右子树)
for (int j = size - 1; j >= 0; j--) {
String opposite = lastFolds.get(j).equals("凹") ? "凸" : "凹";
currentFolds.add(opposite);
}
lastFolds = currentFolds; // 更新为当前序列
}
return lastFolds;
}
}
public class MainChecker {
// ===================================================
// 你的被测方法(需要修改为返回 List<String> 以便比较)
// ===================================================
// ===================================================
// 暴力解(标准答案生成器)- 沿用上面的 FoldChecker.getStandardFolds(int N)
// ===================================================
// ... 将 FoldChecker 类的 getStandardFolds 方法包含进来
// ===================================================
// 对数器主程序
// ===================================================
public static void main(String[] args) {
int testTime = 1000;
// 对于“折纸问题”,对数器中的 N 值通常不能超过 20 到 25,这取决于您的 JVM 默认分配的堆内存大小。
int maxN = 20;
Random random = new Random();
boolean success = true;
System.out.println("开始对数器测试...");
for (int i = 0; i < testTime; i++) {
// N 值不宜过大,10次对折序列长度为 2^10 - 1 = 1023
int N = random.nextInt(maxN) + 1;
// 1. 获取标准答案
List<String> standard = FoldChecker.getStandardFolds(N);
// 2. 获取被测方法的输出
List<String> actual = printAllFolds(N);
// 3. 比较结果
if (!standard.equals(actual)) {
success = false;
System.out.println("----------------- ❌ 失败!-----------------");
System.out.println("N = " + N);
System.out.println("标准答案 (Standard): " + standard);
System.out.println("被测方法 (Actual): " + actual);
break;
}
}
if (success) {
System.out.println("----------------- ✅ 成功!-----------------");
System.out.println("通过 " + testTime + " 组测试,恭喜!");
} else {
System.out.println("对数器测试失败。");
}
}
}