編程演算法 - 把數組排成最小的數 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   把數組排成最小的數   代碼   c   

把數組排成最小的數 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


題目: 輸入一個正整數數組, 把數組裡所有數字拼接起來排成一個數, 列印能拼接出的所有數字中最小的一個.


大數轉換為字串, 重載快速排序比較方法, 進行排序, 最後拼接.


代碼:

/* * main.cpp * *  Created on: 2014.6.12 *      Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <stdlib.h>#include <string.h>int compare(const void* strNumber1, const void* strNumber2) {const int MaxNumberLength = 10;char* strCombine1 = new char[MaxNumberLength*2 + 1];char* strCombine2 = new char[MaxNumberLength*2 + 1];strcpy(strCombine1, *(const char**)strNumber1);strcat(strCombine1, *(const char**)strNumber2);strcpy(strCombine2, *(const char**)strNumber2);strcat(strCombine2, *(const char**)strNumber1);int result = strcmp(strCombine1, strCombine2);delete[] strCombine1;delete[] strCombine2;return result;}void PrintMinNumber (int* numbers, int length) {const int MaxNumberLength = 10;if (numbers == NULL || length <= 0)return;char** strNumbers = (char**)(new int[length]);for (int i=0; i<length; ++i) {strNumbers[i] = new char[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;}int main(void){    int input[] =  {3, 32, 321};    PrintMinNumber(input, 3);    return 0;}


輸出:

321323





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.