Interview question: Arrange the array into the smallest number

Source: Internet
Author: User
Tags stringbuffer

Title Description: 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.

The point is to rewrite the comparator function

Code:

Importjava.util.ArrayList;ImportJava.util.Comparator;Importjava.util.Arrays; Public classSolution { PublicString Printminnumber (int[] numbers) {        if(numbers==NULL|| numbers.length==0)return""; intlen=numbers.length; string[] Str=NewString[len]; StringBuffer SB=NewStringBuffer ();  for(inti=0;i<len;i++) {Str[i]=string.valueof (Numbers[i]); }        //overriding the comparator functionArrays.sort (str,NewComparator<string>(){             Public intCompare (string s1,string s2) {string C1=s1+S2; String C2=s2+S1; returnC1.compareto (C2);        }        });  for(inti=0;i<len;i++) {sb.append (str[i]); }        returnsb.tostring (); }}

Interview question: Arrange the array into the smallest number

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.