日期:2014-05-20 浏览次数:20868 次
class test1{
private int[] resultArray; // split result.
private int flag;
test1(int length){
resultArray = new int[length];
}
public static void main(String[] args){
/* opera */
int splitRes = 25;
/* split */
test1 split = new test1(splitRes/6 + 2);
split.split(splitRes);
/* result output */
System.out.println("input =" + splitRes);
for(int i =0; i < split.flag; i ++){
System.out.println("resultArray[" + i + "] = " + split.resultArray[i]);
}
}
/* split */
void split(int splitRes){
if (splitRes >= 6){
splitRes -= 6;
resultArray[flag] = 6;
flag += 1;
split(splitRes);
}else if( splitRes >=4 ){
splitRes -= 4;
resultArray[flag] = 4;
flag += 1;
split(splitRes);
}else if( splitRes >=2){
splitRes -= 2;
resultArray[flag] = 2;
flag += 1;
split(splitRes);
}else if( splitRes >=1){
splitRes -= 1;
resultArray[flag] = 1;
flag += 1;
split(splitRes);
}
}
}
------解决方案--------------------
public class split2 {
public static void main(String[] args) {
int amountOf6 = 0; // the Numbers of 6.
int amountOf4 = 0; // the Numbers of 4.
int amountOf2 = 0; // the Numbers of 2.
int amountOf1 = 0; // the Numbers of 1.
int pos = 0;
/* opera*/
int splitRes = 27; //change the NO. here.
int[] resultArray = new int[splitRes/6 + 2];
System.out.println("input =" + splitRes);
/* count the Numbers of 6. */
amountOf6 = splitRes/6 ;
splitRes = splitRes%6;
for (int i =0 ; i< amountOf6 ; i++ ){
resultArray[i] = 6;
}
/* count the Numbers of 4. */
amountOf4 = splitRes/4 ;
splitRes = splitRes%4;
for (int i =0 ; i< amountOf4 ; i++ ){
resultArray[i +amountOf6] = 4;
}
/* count the Numbers of 2. */
amountOf2 = splitRes/2 ;
splitRes = splitRes%2;
for (int i =0 ; i< amountOf2 ; i++ ){
resultArray[i+ amountOf6+amountOf4] = 2;
}
/* count the Numbers of 1. */
if (splitRes==1){
amountOf1 = 1;
resultArray[amountOf6+amountOf4+ amountOf2] = 1;
}
/* result output */
for(int i =0; i < resultArray.length; i++){
System.out.println("resultArray[" + i + "] = " + resultArray[i]);
}
}
}