合并连续数字的算法

合并连续数字的算法

public class Test {
	public static void main(String[] args) {
		String str = new String(
				"1,2,3,4,5,6,7,8,9,11,13,14,1000,1001,1002,1003");
		String[] s = str.split(",");
		int[] num = new int[s.length];
		String result = "";
		for (int i = 0; i < s.length; i++) {
			num[i] = Integer.parseInt(s[i]);
		}
		for (int i = 0; i < num.length; i++) {
			if (i == 0) {
				result = "" + num[i];
			} else if (i == num.length - 1) {
				if (num[i] - num[i - 1] == 1) {
					result = result + "-" + num[i];
				} else {
					result = result + "," + num[i];
				}
			} else {
				if ((num[i] - num[i - 1] == 1) && (num[i + 1] - num[i] == 1)) {
					continue;
				}
				if ((num[i] - num[i - 1] == 1) && (num[i + 1] - num[i] != 1)) {
					result = result + "-" + num[i];
				}
				if ((num[i] - num[i - 1] != 1)) {
					result = result + "," + num[i];
				}

			}

		}
		System.out.println(result);
	}
}
作者:caoyinghui1986 发表于2008-5-31 14:11:00 原文链接
阅读:288 评论:1 查看评论

你可能感兴趣的:(合并连续数字的算法)