题目:
输入一个正整数数组,把数组中所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个,例如输入数组{3,32,321},则打印出这3个数字中能排成的最小数字321323
算法如下:
public class Solution {
public String PrintMinNumber(int [] numbers) {
StringBuffer buffer = new StringBuffer();
sort(numbers,0,numbers.length-1);
for(int i=0;i<numbers.length;i++){
buffer.append(numbers[i]);
}
return buffer.toString();
}
//定义两个整数的比较函数
public boolean compare(int a,int b){
String str1 = "";
String str2 = "";
str1 = str1+a;
str2 = str2+b;
int i=0;
int min = minLen(str1,str2);
for(;i<min&&str1.charAt(i)!='\0'&&str2.charAt(i)!='\0';i++){
if(str1.charAt(i)==str2.charAt(i)){
}else{
if(str1.charAt(i)-str2.charAt(i)>0){
return true;
}else{
return false;
}
}
}
if(str1.length()<str2.length()){
return compare(str1.charAt(i-1),str2.charAt(i));
}else if(str1.length()>str2.length()){
return compare(str1.charAt(i),str2.charAt(i-1));
}else{
return true;
}
}
//计算两个字符串最小位数
public int minLen(String str1,String str2){
int temp1 = str1.length();
int temp2 = str2.length();
if(temp1>=temp2){
return temp2;
}else{
return temp1;
}
}
//计算n的位数
public int count(int n){
int count = 0;
if(n!=0){
count++;
}
while(n/10!=0){
count++;
n = n/10;
}
return count;
}
//快速排序
public void sort(int[] a,int low,int high){
if(low>=high){
return;
}
int i=low;
int j=high;
int index = a[i];
while(i<j){
while(i<j&&compare(a[j],index)){
j--;
}
if(i<j){
a[i++] = a[j];
}
while(i<j&&compare(index,a[i])){
i++;
}
if(i<j){
a[j--] = a[i];
}
a[i] = index;
sort(a,low,i-1);
sort(a,i+1,high);
}
}
}