Java 之 数字排列
题目:用1、2、3、4、5这五个数字,打印出所有不同的数字排列,如:51234、41235、31254等,要求:"4"不能在第三位,"3"与"5"不能相连,一个排列中数字不能重复。
题目分析:该五个数字组合实际上是一个数,这个数中最大为54321,最小为12345,因此可以用循环遍历出来。
编程实现:
public class RankNumber{
private static String [] number = new String [] {"1","2","3","4","5"};
private static boolean conditionsCheck(String str){
for(String number:number){//检查是否包含该五个数,不包含返回false
if(str.indexOf(number)<0){
return false;
}
if(str.charAt(2) == '4'){// 检查4在不在第三位,是:返回false
return false;
}
if(str.indexOf("35")>=0 || str.indexOf("53")>=0){// 检查是否存在3和5在一起,是:返回false
return false;
}
}
return true;
}
public static void main(String args[]){
System.out.println("可组成的数字排列:");
for(int i=12345; i<=54321; i++){
if(conditionsCheck(String.valueOf(i))){
System.out.print(i+" ");
}
}
}
}