Put the array into the smallest number-the sword refers to the offer

Source: Internet
Author: User

To arrange the array into the smallest number of questions.

Enter an array of positive integers, combine all the numbers in the array into a number, and print the smallest of all the numbers that can be stitched together. For example, enter the array {3,32,321}, then print out the minimum number that these three numbers can be ranked as 321323.

Ideas
    1. The number of two int can be larger, overflow, we can use a string to represent, handle the large number of problems
    2. Convert a number to a string, and then compare the size of the string, where the size refers to: if STR1+STR2 > Str2+str1, then str1 > str2, we need to redefine a compare function
    3. In fact, the final connection size and string comparison of the size of the rules are the same.
Code
Import Java.util.ArrayList;public class Solution {publicString printminnumber (int [] numbers) {string[] Numstr = newstring[numbers.length];for (int i =0; i < numbers.length; i++) {Numstr[i] =String.valueof (Numbers[i]);}Selectsort (NUMSTR);StringBuilderSTRB = newStringBuilder (); for (int j =0; J < Numstr.length; J + +) {Strb.append (Numstr[j]);} ReturnStrb.tostring (); }public int Comparestr (StringSTR1,StringSTR2) {StringBuilder SB1 = newStringBuilder ();StringBuilder SB2 = newStringBuilder (); Sb1.append (STR1); Sb1.append (STR2); Sb2.append (STR2); Sb2.append (STR1); return sb1.tostring (). CompareTo (Sb2.tostring ());} public voidselectsort (string[] data) {for (int i = 0; for (int j = Span class= "Hljs-preprocessor" >data.length-1; J >i; j--) { Span class= "Hljs-preprocessor" >if (comparestr (data[j], data[k]) < 0) k = J;} string temp = data[i] data[i] = data[k] data[k] = Temp;}}        

Line up the array to the smallest number-the sword refers to the offer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.