题目:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接处的所有数字中的最小的一个。例如,输入数组{3,32,321},则打印出这3个数字能排成的最小数字321323。
链接:https://www.nowcoder.com/questionTerminal/8fecd3f8ba334add803bf2a06af1b993
来源:牛客网
在这里自定义一个比较大小的函数,比较两个字符串s1, s2大小的时候,先将它们拼接起来,比较s1+s2,和s2+s1那个大,如果s1+s2大,那说明s2应该放前面,所以按这个规则,s2就应该排在s1前面。
(这个方法会改变原数组)
package offer;
import java.util.Scanner;
public class Solution45 {
public String PrintMinNumber(int[] numbers) {
String str = "";
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
int a = Integer.valueOf(numbers[i] + "" + numbers[j]);
int b = Integer.valueOf(numbers[j] + "" + numbers[i]);
if (a > b) {
int t = numbers[i];
numbers[i] = numbers[j];
numbers[j] = t;
}
}
}
for (int i = 0; i < numbers.length; i++) {
str += String.valueOf(numbers[i]);
}
return str;
}
public static void main(String[] args) {
Solution45 sl = new Solution45();
Scanner scanner = new Scanner(System.in);
System.out.print("数组元素个数为:");
int len = scanner.nextInt();
int[] numbers = new int[len];
System.out.println("请输入一个数组:");
for (int i = 0; i < len; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println("最小的数为:" + sl.PrintMinNumber(numbers));
}
}
Integer.valueOf()方法
https://blog.csdn.net/dawn_after_dark/article/details/74154338