[Leetcode] Largest number

Source: Internet
Author: User

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9] , the largest formed number is 9534330 .

Note:the result May is very large, so you need to return a string instead of an integer.

This topic took a lot of time at first, and the train of thought is not good. Converts a number to a string, allowing strings of different lengths to be compared from left to right by character. But if a string is another prefix, even if the extra string is compared to the first character, there are still a lot of things to deal with.

The simplest way to do this is to compare s1+s2 and s2+s1 when comparing two strings S1 and S2. Note that there is a special case where the combined string starts at 0 and needs to be removed from the beginning of the 0.


    Class Stringcomparator implements comparator<string> {@Overridepublic int compare (string s1, string s2) {string S12 = s1 + s2; String S21 = s2 + s1;return (int) (Long.parselong (S12)-Long.parselong (S21));}}            Public String largestnumber (int[] num) {StringBuilder sb = new StringBuilder (); list<string> numstr = new arraylist<string> (); for (int i:num) {Numstr.add ("" + i);} Collections.sort (Numstr, New Stringcomparator ());        <span style= "White-space:pre" ></span>//Trim the leading zero (s). Boolean HASPOSSIBLELEADING0 = True;for ( int i = Numstr.size ()-1; I >= 0; -i) {if (HasPossibleLeading0 && numstr.get (i). Equals ("0")) continue; HASPOSSIBLELEADING0 = False;sb.append (Numstr.get (i));} if (sb.length () = = 0) {return "0";} return sb.tostring ();    }






[Leetcode] Largest 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.