日期:2014-05-20  浏览次数:20645 次

大家帮帮忙,如何从一组数字取出连续的数字?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);
}
}


大概这个思路,楼主根据情况改改吧.
------解决方案--------------------

int []a={0,1,2,4,5,6,9,10};

for (int i = 0; i < a.length; i++) {
if(i==0)
{
System.out.print(a[i]+"-");
}
else if(a[i]==a[i-1]+1)
{

if(i<a.length-1)
continue;
else
System.out.println(a[i]);

else
        {   System.out.println(a[i-1]);
System.out.print(a[i]+"-");
        }
}
------解决方案--------------------

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++) {