1. 程式人生 > >輸入一個正整數陣列,把數組裡所有數字拼接起來排成一個數, 列印能拼接出的所有數字的最小的一個。例如輸入{3,32,321,4},則列印最小的數字是 3213234

輸入一個正整數陣列,把數組裡所有數字拼接起來排成一個數, 列印能拼接出的所有數字的最小的一個。例如輸入{3,32,321,4},則列印最小的數字是 3213234

public class FandMax {

public void makeMax(int[] nums){
	boolean flag=true;
	for (int i = 0; i < nums.length; i++) {
		for (int j = 0; j < nums.length-i-1; j++) {
			if(compare(nums[j],nums[j+1])){
				swap(nums, j, j+1);
				flag=false;
			}
		}
		if(flag){
			return;
		}else {
			flag=true;
		}
	}
}

/**
 * 需要交換返回true不需要返回false
 * 11 12 不需要交換 2 20 需要交換
 */
public boolean compare(int n1, int n2) {
	int temp1=Integer.parseInt(n1+""+n2);
	int temp2=Integer.parseInt(n2+""+n1);
	if(temp1>temp2){
		return true;
	}else {
		return false;
	}
}

/**
 * 交換兩個數
 */
public void swap(int nums[],int key1,int key2){
	int temp;
	temp=nums[key1];
	nums[key1]=nums[key2];
	nums[key2]=temp;
}

public static void main(String[] args) {
	int nums[]={2,18,21,45};
	FandMax fandMax=new FandMax();
	fandMax.makeMax(nums);
	for (int i = 0; i < nums.length; i++) {
		System.out.println(nums[i]);
	}
}

}