我需要编写一个名为consecutive的方法,该方法接受6个参数来检查6个输入是否是连续数,而不管顺序如何。如果数字是连续的,则返回true,否则返回false。有人可以教我这样做的最有效方法是什么?我尝试过这种方法,但如果我有6个数字会效率低吗?
public static boolean consecutive(int numberOne,int numberTwo,int numberThree) {
if(((numberTwo==numberOne-1) && (numberThree== numberTwo-1)) || ((numberTwo==numberOne+1) && (numberThree==numberTwo+1)) || ((numberTwo==numberOne+2) &&( numberThree==numberOne+1)) || ((numberTwo==numberOne-1)&& (numberThree==numberOne+1)) || ((numberTwo==numberOne-2) && (numberThree==numberOne-1)) ||((numberTwo==numberOne+1) && (numberThree==numberOne-1))){
return true;
}else{
return false;
}
}
}
答案 0 :(得分:5)
将值添加到数组中,对数组进行排序,然后测试一组连续的值:
int[] test = new int[] {numberOne, numberTwo, etc...};
Arrays.sort(test);
for (int i = 0; i < test.length - 1; i++) {
if (test[i] + 1 != test[i + 1]) {
// Not sequential
}
}
答案 1 :(得分:1)
增强@Chris的答案,假设没有重复的数字:
public static boolean consecutive(
int numberOne,int numberTwo,int numberThree,
int numberFour, int numberFive, int numberSix) {
int [] ns = {
numberOne, numberTwo, numberThree,
numberFour, numberFive, numberSix };
Arrays.sort(ns);
return ( ns[ns.length-1] - ns[0] == ns.length-1 );
}