ECNU || 和你在一起

思路

看到题目首先想到如何使两个数连接在一起最大,例如12和456,连接在一起有两种情况分别为12456和45612,显然后者比前者大。
如果是多个正整数连在一起呢,我们需要对元素进行比较,很显然这是一个排序的过程,而且需要相邻的元素两两比较,选择冒泡排序。
即:如果是三个数字456,12,342,78,
1.我们需要比较12和456,发现45612比12456大,此时交换两个数字 12,456,342,78
2.再比较456342和342456,前者比后者大,再进行交换得到12,342,456,78
3.再比较45678和78456,前者比后者小,不进行交换,此时一趟排序已经结束,最小的元素12已经放在最前面。
4.重复上面步骤第二趟排序得到12,342,456,78.
5.此时其实已经很明显冒泡排序完成,
分析到这其实发现要想连接到一起的数字最大,我们其实需要排序的是每个数字的第一位,就像上面的例子,最终每个数字的第一位排序得到1,3,4,7;
这样只是更直观的说明这道题目。
综上所述我们的解题思路就是在相邻两个正整数连接起来比较大小的基础上再对所有数字冒泡排序,即可完成题目要求。

原文:https://blog.csdn.net/liyf__88/article/details/77587546

代码

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Main main = new Main();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[] = new int[n];
        for(int i = 0; i < arr.length; i++){
            arr[i] = sc.nextInt();
        }
        int tmp;
        for(int i = 0; i < n; i++){
            for(int j = 0; j< n-i-1; j++){
                if(main.Compare(arr[j] , arr[j+1])){
                    tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                }
            }
        }
        for(int i = n-1; i >= 0; --i){
            System.out.print(arr[i]);
        }
    }
    public boolean Compare(int num1, int num2){
        int count1 = 0, count2 = 0;
        int nm1 = num1, nm2 = num2;
        while(nm1!=0){
            count1++;
            nm1/=10;
        }
        while(nm2!=0){
            count2++;
            nm2/=10;
        }
        int a = num1 * (int)Math.pow(10.0, count2) + num2;
        int b = num2 * (int)Math.pow(10.0, count1) + num1;
        
        return a>b? true:false;
    }
}

知识

⭐调用函数

public class Main {
    public static void main(String[] args) {
        Main main=new Main();
        System.out.println(main.MaxNum(arr));
    }
    public int MaxNum(String[] str){
    	return ret;
    }

⭐不换行输出

System.out.print();

⭐平方

Math.pow(x,y)
结果是浮点型的,可以用(int)强制类型转换

⭐冒泡排序

https://www.cnblogs.com/shen-hua/p/5422676.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值