caoyinghui

合并连续数字的算法

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 查看评论

posted on 2008-05-31 06:11 shine_panda 阅读(257) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2008年5月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜