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

Chuyển đổi số nguyên dương thành chữ (Number to Words) trong C++

Cho số nguyên dương (≤ 1 tỷ). Chuyển thành chữ tiếng Anh: ví dụ 5678 → "Five Thousand Six Hundred Seventy Eight".

Phương pháp: Đệ quy với bảng tra từ điển

  • Mảng pairs chứa {từ, giá trị}: Billion(1e9), Million(1e6), Thousand(1e3), Hundred(100), Ninety(90)... One(1).
  • Hàm solve(n):
    • Nếu n==0 → "Zero".
    • Duyệt bảng từ lớn đến nhỏ: tìm giá trị ≤ n.
    • Nếu giá trị ≥ 100: đệ quy solve(n/val) + " " + từ + (n%val ? " " + solve(n%val) : "").
    • Ngược lại: từ + (n>val ? " " + solve(n-val) : "").

Ví dụ mã C++

#include <bits/stdc++.h>
using namespace std;

vector> dict = {
    {"Billion",1000000000}, {"Million",1000000}, {"Thousand",1000}, {"Hundred",100},
    {"Ninety",90}, {"Eighty",80}, {"Seventy",70}, {"Sixty",60}, {"Fifty",50},
    {"Forty",40}, {"Thirty",30}, {"Twenty",20}, {"Nineteen",19}, {"Eighteen",18},
    {"Seventeen",17}, {"Sixteen",16}, {"Fifteen",15}, {"Fourteen",14}, {"Thirteen",13},
    {"Twelve",12}, {"Eleven",11}, {"Ten",10}, {"Nine",9}, {"Eight",8}, {"Seven",7},
    {"Six",6}, {"Five",5}, {"Four",4}, {"Three",3}, {"Two",2}, {"One",1}
};

string solve(int n) {
    if (n == 0) return "Zero";
    for (auto &p: dict) {
        if (p.second <= n) {
            string res;
            if (p.second >= 100) {
                res = solve(n / p.second) + " " + p.first;
                if (n % p.second) res += " " + solve(n % p.second);
            } else {
                res = p.first + (n > p.second ? " " + solve(n - p.second) : "");
            }
            return res;
        }
    }
    return "";
}

int main() {
    cout << solve(5678) << endl; // Five Thousand Six Hundred Seventy Eight
    return 0;
}

Đầu ra chương trình

Five Thousand Six Hundred Seventy Eight