Title Description
Set nn positive integers (n≤20) (n≤20), connect them in a row to form a largest multi-digit integer.
For example: when n = 3, the maximum integer of three integers 13,312,343 is: 34313213
Another example: when n = 4, the maximum number of four integers 7,13,4,246 connected is: 7424613
Input format The
first line, a positive integer nn.
The second line, nn positive integers.
Output format
A positive integer representing the largest integer
Problem idea: The idea of this problem is to use string exchange to solve the problem, and it is also applied to bubble sorting. For
example, the string a, b is exchanged when a + b <b + a, and the big one is guaranteed to be placed first. Below is the code
import java.util.Scanner;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String s1 = input.nextLine();//接受回车字符
String str = input.nextLine();
String[] array = str.split(" ");
/*不是很推荐使用split,最好还是直接创建一个数组,之后赋值
主要是因为容易犯小错误,nextInt()是不会接受回车的,所以
str字符串直接接受了回车就会导致数组下标越界
*/
for(int i = 0; i < n-1;i++ ) //应用冒泡
{
for(int j = 0; j < n-1-i; j++)
{
if(isLarge(array[j],array[j+1]))
{
String temp ="";
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for(int i = 0; i < n; i++)
System.out.print(array[i]);
}
public static boolean isLarge(String s1,String s2)
{
/*这个是本题的核心,交换字符串,当a+b < b+a的时候
将b换到a前面
*/
int temp = Integer.parseInt(s1+s2);
int temp1 = Integer.parseInt(s2+s1);
if(temp1 > temp)
return true;
else
return false;
}
}
I hope everyone has to help