字符串数字从小到大输出

题目:将一个随机的整数转换成一个按各位上数值大小排序的整数,例如整数2541转换成1245,随机整数521368转换成123568,要求不能使用一步到位的库函数.

答:

#include "stdafx.h"
#include <iostream>

using namespace std;

//字符串数字从小到大输出
void Solution(char *str)
{
    if (NULL == str)
    {
        return;
    }
    unsigned int hashTab[10] = {0};
    char *p = str;
    while (*p != '\0')
    {
        hashTab[*p++ - '0']++;
    }
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < hashTab[i]; j++)
        {
            *str++ = i + '0';
        }
    }
    *str = '\0';
}

int _tmain(int argc, _TCHAR* argv[])
{
    char str[] = "999988888844447777122222333336666666666666664444444444488555555555";
    cout<<"before: "<<str<<endl;
    Solution(str);
    cout<<"after:  "<<str<<endl;

    cout<<endl;
    return 0;
}

运行界面如下:

原文地址:https://www.cnblogs.com/venow/p/2672119.html