Interview 33: Arrange the array into the smallest number

Source: Internet
Author: User

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, the input array {3,32,321} prints out the smallest number 321323 that these 3 numbers can be ranked.

Problem analysis

Sword means offer (Commemorative edition) P177

Code implementation
int integers represent up to 10-bit const int g_maxnumberlength = 10 in decimal notation; char* g_strcombine1 = new Char[g_maxnumberlength * 2 + 1];char* g_strcombine2 = new Char[g_maxnumberlength * 2 + 1];     void Printminnumber (int* numbers, int length) {if (numbers = = NULL | | length <= 0) return;    char** strnumbers = (char**) (new int[length]);        for (int i = 0; i < length; ++i) {strnumbers[i] = new Char[g_maxnumberlength + 1];    sprintf (Strnumbers[i], "%d", numbers[i]);     } qsort (strnumbers, length, sizeof (char*), compare);    for (int i = 0; i < length; ++i) printf ("%s", Strnumbers[i]);     printf ("\ n");    for (int i = 0; i < length; ++i) delete[] strnumbers[i]; Delete[] strnumbers;} If [Strnumber1][strnumber2] > [Strnumber2][strnumber1], the return value is greater than 0//if [strnumber1][strnumber2] = [strnumber2][ StrNumber1], the return value equals 0//if [Strnumber1][strnumber2] < [Strnumber2][strnumber1], the return value is less than 0int compare (const void* StrNumber1, const void* strNumber2) {//[strnumber1][StrNumber2] strcpy (G_STRCOMBINE1, * (const char**) strNumber1);     strcat (G_STRCOMBINE1, * (const char**) strNumber2);    [Strnumber2][strnumber1] strcpy (g_strcombine2, * (const char**) strNumber2);     strcat (G_STRCOMBINE2, * (const char**) strNumber1); Return strcmp (G_strcombine1, g_strcombine2);}

  

Interview 33: 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.