數組中的跳躍問題

本文翻譯自stackoverflow,by:王奎

問題:我有一個數組:

[1,2,3,6,7, 8, 9,20, 22]

我想讓它對用戶以下形式顯示

Numbers 1 through 3, 6 through 9, 20, 22
下面是一個完整是程序:

/**
	blog:http://www.marksaas.com
	author :marksaas
	
*/
public class ArrayTest{
public static void main(String[] args){
Integer[] A = {1, 2, 3, 6, 7, 8, 9, 20, 22};
System.out.print("Numbers ");
int start = 0, end;
while(start < A.length){
    System.out.print(A[start]);
    end = start;
    while(end + 1 < A.length && A[end + 1] == A[end] + 1)
        end++;
    System.out.print((end == start ? "":(" through " + A[end])) + ", ");
    start = end + 1;
}
	}
}
歡迎關注我的微博  ,我的微博會實時更新文章。  交流羣: 

199326422



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章