Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm số lớn nhất tạo được từ các chữ số cho trước trong C++


Cho mảng chữ số, tìm số lớn nhất dùng hết các chữ số. Ví dụ [3,3,9,6,2,5] → 965332.

Sắp xếp giảm dần hoặc đếm tần suất chữ số 0-9, sau đó in từ 9 xuống 0.

Ví dụ

#include <iostream> #include <string> using namespace std; int maxNumFromNum(int arr[], int n) {    int freq[10] = {0};    for (int i=0; i<n; i++)    freq[arr[i]]++;    int res = 0, mul = 1;    for (int i = 0; i <= 9; i++) {       while (freq[i] > 0) {          res = res + (i * mul);          freq[i]--;          mul = mul * 10;       }    }    return res; } int main() {    int digits[] = {3, 3, 9, 6, 2, 5};    int n = sizeof(digits)/sizeof(digits[0]);    cout << "Maximum number: " << maxNumFromNum(digits, n); }

Kết quả

Maximum number: 965332