百词斩的第二道编程题,题目不难,事后码出来了,留个档。

题目:

给定一组1~7组成(包含1和7)的有序且非重复数字数组, 每个数字的字面值n表示一周里面的第n天, 要求按照如下规则压缩后, 输出压缩以后的描述:

1) 对于三个及三个以上的连续数字, 需要压缩成”起始-结束”的格式;

2) 对于三个以下的连续或不连续数字, 不需要压缩, 按照原样输出;

输入:

第一行输入n,为数组的长度,比如5天的话,n=5,接下几行为具体的星期

如:

3 (3天)
1 (星期一)
2 (星期二)
4 (星期四)

输出:

压缩后的数字序列,序列的每一段之间使用英文逗号分隔。

如输入:

5
1
2
4
5
6

则输出:

1,2,4-6

具体Java代码实现:

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
class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
check(array);
}
public static void check(int[] array) {
//记录连续数的开头值
int min = 0;
//标记当前数是否与前一个连续
int flag = 0;
//连续数的个数 题目要求超过3个才用 "-" 连接
int count = 0;
//记录结果
String result = "";
for (int i = 0; i < array.length; i++) {
//遍历到最后一个数的情况
if (i == array.length - 1) {
if (flag == 0) { //与前面的数不连续
result += array[i];
} else { //与前面的数连续
if (count >= 2) { //超过3个连续数 用 - 连接
result += min + "-" + array[i];
} else {
result += min + "," + array[i];
}
}
break;
}
//非最后一个数
if (array[i] + 1 != array[i + 1]) {
if (flag == 0) { //当前数前后都不连续
result += array[i] + ",";
} else { //当前数与前一个连续但与后一个不连续的情况
if (count >= 2) {
result += min + "-" + array[i] + ",";
} else {
result += min + "," + array[i] + ",";
}
//重置计算
min = 0;
count = 0;
flag = 0;
}
} else {
if (flag == 0) { //当前数与前一个不连续与后一个连续
min = array[i];
count = 1;
flag = 1;
} else { //当前数前后都连续
count++;
}
}
}
System.out.println(result);
}
}