合并连续数字的算法

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);
	}
}
展开阅读全文
©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值