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

答题
一串数字,1,4,5,6,8,9,10,13,14,15,16

怎么判断它是不是连续的,如果连续返回true,否则,false

------解决方案--------------------
public static void main(String[] args) {
  String str1 = "1,2,3,4,5,6,7,8,10 ";
  String str2 = "1,2,3,4,5,6,7,8,9,10 ";
  System.out.println(isSeriateNumber(str1, ", "));
  System.out.println(isSeriateNumber(str2, ", "));
}

// 假定序列是数字顺序是升序的
// 只要获得第一值和最后一个值,通过其数值数计算一下,就可以得出是否是连的
private static boolean isSeriateNumber(String strNum, String separator) {
  String[] strNums = strNum.split(separator);
  int start = Integer.parseInt(strNums[0]);
  int end = Integer.parseInt(strNums[strNums.length-1]);
  if(start + strNums.length - 1 == end){
    return true;
  }else{
    return false;
  }
}
------解决方案--------------------
楼上的代码不准确

如果是这样 。。。。。。。。。。。。

public class test
{
public static void main(String[] args) {
String str1 = "1,2,3,4,9,5,6,7,8,10 "; /////这里把9加到了4后面
String str2 = "1,2,3,4,5,6,7,8,9,10 ";
System.out.println(isSeriateNumber(str1, ", "));
System.out.println(isSeriateNumber(str2, ", "));
}

// 假定序列是数字顺序是升序的
// 只要获得第一值和最后一个值,通过其数值数计算一下,就可以得出是否是连的
private static boolean isSeriateNumber(String strNum, String separator) {
String[] strNums = strNum.split(separator);
int start = Integer.parseInt(strNums[0]);
int end = Integer.parseInt(strNums[strNums.length - 1]);
if (start + strNums.length - 1 == end) {
return true;
} else {
return false;
}
}

}
------解决方案--------------------
那就改一下,增加一个排序。

public static void main(String[] args) {
  String str1 = "1,2,3,4,5,6,7,8,10 ";
  String str2 = "2,3,4,5,6,7,8,9,10 ";
  String str3 = "2,3,4,9,5,6,7,8,10 ";
  System.out.println(isSeriateNumber(str1, ", "));
  System.out.println(isSeriateNumber(str2, ", "));
  System.out.println(isSeriateNumber(str3, ", "));
}

private static boolean isSeriateNumber(String strNum, String separator) {
  String[] strNums = strNum.split(separator);
  int[] nums = new int[strNums.length];
  for(int i=0; i <strNums.length; i++) {
    nums[i] = Integer.parseInt(strNums[i]);
  }
  Arrays.sort(nums);    
  if(nums[0] + nums.length - 1 == nums[nums.length-1]){
    return true;
  }else{
    return false;
  }
}
------解决方案--------------------
呵呵,再次订正一下,由于先前没有考虑到重复的问题,看来只能逐一进行比较了。

public static void main(String[] args) {
  String str1 = "1,2,3,4,5,6,7,8,10 ";
  String str2 = "2,3,4,5,6,7,8,9,10 ";
  String str3 = "2,3,4,5,6,7,9,8,10 ";
  String str4 = "2,4,4,5,6,7,9,8,10 ";
  String str5 = "2,3,4,5,6,7,8,10,10 ";
  System.out.println(isSeriateNumber(str1, ", "));
  System.out.println(isSeriateNumber(str2, ", "));
  System.out.println(isSeriateNumber(str3, ", "));
  System.out.println(isSeriateNumber(str4, ", "));
  System.out.println(isSeriateNumber(str5, ", "));
}

private static boolean isSeriateNumber(String strNum, String separator) {
  String[] strNums = strNum.split(separator);
  int[] nums = new int[strNums.length];
  for (int i = 0; i < strNums.length; i++) {