大家帮帮忙,如何从一组数字取出连续的数字?100分哈
0 1 2 4 5 6 9 10
取出来变成这样
0-2
4-6
9-10
[解决办法]
需求不明确,是字符串,还是数组,取出来是连续,还是跳跃?
[解决办法]
同意楼上的,赶紧把需求说明白吧
如果是跳一个数字取的话,你的步进+2就可以了。
[解决办法]
public static void main(String[] args) throws Exception {
int[] arr = new int[]{0,1,2,4,5,6,9,10};
String s = "" + arr[0];
int last = arr[0];
for(int i = 1; i < arr.length;i++){
if(arr[i] - last == 1){
;
}else{
System.out.println(s + "-" + last);
s = "" + arr[i];
}
last = arr[i];
}
if(!s.equals("" + last)){
System.out.println(s + "-" + last);
}
}
public class Test03 {
static final int[] arr = new int[] { 0, 1, 2, 4, 5, 6, 9, 10 };
public static void main(String[] args) {
takeOut(arr);
}
static void takeOut(int[] arr) {
//假设数组是连续的
int start = 0, end = start;
for (int i = 1; i < arr.length; ++i) {
if (arr[i] - arr[end] == 1) {
end = i;
} else {
System.out.printf("%d-%d\n", arr[start], arr[end]);
start = i;
end = start;
}
}
//打印最后一组数据
System.out.printf("%d-%d\n", arr[start], arr[end]);
}
}
public class Test {
public static void main(String[] args)
{
int[] i = {0, 1, 2, 4, 5, 6, 9, 10};
int tmp = -1;
for (int j = 0; j < i.length; j++) {
if (tmp==-1){
tmp=i[j];
System.out.print(tmp+"-");
}else if (tmp+1==i[j]){
tmp=i[j];
}else if(tmp+1<i[j]){
System.out.println(tmp);
System.out.print(i[j]+"-");
tmp=i[j];
}
if(j==i.length-1){
System.out.println(tmp);
}
}
}
}