Giới thiệu
Thuật toán này sẽ chuyển đổi một số cho trước thành từ tiếng Anh. Ví dụ 564 sẽ thành "Five Hundred and Sixty-Four".
Đối với thuật toán này, một số chuỗi được định nghĩa trước, từ danh sách đó, nó sẽ lấy các từ thích hợp để tạo thành từ.
Các danh sách như sau:
- Units: chứa tất cả từ cho (0 đến 9) như Zero, One... Nine
- twoDigits: chứa tất cả số từ (10 - 19), như Ten, eleven... Nineteen
- tenMul: Cho bội số của 10, (20-90), như Twenty, Thirty,... Ninety.
- tenPower: Dùng cho Hundred và Thousands như lũy thừa 2 và 3 của 10
Đầu vào và Đầu ra
Đầu vào: Số: 568 Đầu ra: Five Hundred And Sixty Eight
Thuật toán
numToWord(num)
có một số danh sách chứa từ cho các số nguyên khác nhau
Đầu vào: Số.
Đầu ra: Biểu diễn số thành từ.
Begin
if n >= 0 and n < 10, then
hiển thị units(n) thành từ
else if n >= 10 and n < 20, then
hiển thị twoDigitNum(n) thành từ
// Từ mười đến mười chín
else if n >= 20 and n < 100, then
hiển thị tensMultiple(n/10), thành từ
if n mod 10 ≠ 0, then
numToWord(n mod 10)
else if n >= 100 and n < 1000, then
hiển thị units(n/100), thành từ
hiển thị "Hundred", thành từ
// Hundred
if n mod 100 ≠ 0, then
hiển thị "And"
numToWord(n mod 100)
else if n >= 1000 and n <= 32767, then
numToWord(n/1000)
hiển thị "Thousand"
if n mod 1000 ≠ 0, then
numToWord(n mod 1000)
else
hiển thị invalid number và exit
End
Ví dụ (C++)
#include <iostream>
using namespace std;
string getUnit(int n) {
// Trả về chữ số đơn vị thành từ
string unit[10] = {"Zero", "One","Two", "Three","Four","Five", "Six","Seven","Eight","Nine"};
return unit[n];
}
string getTwoDigits(int n) {
// Ở đây n là số 2 chữ số
string td[10] = {"Ten", "Eleven","Twelve","Thirteen", "Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
return td[n%10];
}
string getTenMul(int n) {
// Ở đây n là bội của 10
string tm[8] = {"Twenty", "Thirty","Fourty", "Fifty","Sixty", "Seventy","Eighty","Ninty"};
return tm[n-2];
}
string getTenPow(int pow) {
// Lũy thừa của mười thành từ
string power[2] = {"Hundred", "Thousand"};
return power[pow-2];
}
void printNumToWord(int n) {
if(n >= 0 && n < 10)
cout << getUnit(n) << " "; // Giá trị đơn vị thành từ
else if(n >= 10 && n < 20)
cout << getTwoDigits(n) << " "; // từ mười một đến mười chín
else if(n >= 20 && n < 100) {
cout << getTenMul(n/10) << " ";
if(n%10 != 0)
printNumToWord(n%10); // Gọi đệ quy chuyển số thành từ
} else if(n >= 100 && n < 1000) {
cout << getUnit(n/100) << " ";
cout << getTenPow(2) << " ";
if(n%100 != 0) {
cout << "And ";
printNumToWord(n%100);
}
} else if(n >= 1000 && n <= 32767) {
printNumToWord(n/1000);
cout << getTenPow(3) << " ";
if(n%1000 != 0)
printNumToWord(n%1000);
} else
printf("Invalid Input");
}
main() {
int number;
cout << "Enter a number between 0 to 32767: "; cin >> number;
printNumToWord(number);
}
Kết quả
Enter a number between 0 to 32767: 568 Five Hundred And Sixty Eight