บทนำ
อัลกอริทึมนี้จะแปลงตัวเลขที่กำหนดให้เป็นคำอ่านภาษาอังกฤษ เช่น 564 จะกลายเป็น Five Hundred and Sixty-Four
สำหรับอัลกอริทึมนี้ มีสตริงที่กำหนดไว้ล่วงหน้า จากรายการนั้น จะนำคำที่เหมาะสมมาสร้างเป็นคำอ่าน
รายการต่างๆ มีดังนี้:
- Units: เก็บคำสำหรับ (0 ถึง 9) เช่น Zero, One... Nine
- TwoDigits: เก็บตัวเลข (10 - 19) เช่น Ten, Eleven... Nineteen
- TenMul: สำหรับพหุคูณของสิบ (20-90) เช่น Twenty, Thirty... Ninety
- TenPower: สำหรับ Hundred และ Thousands เป็นกำลัง 2 และ 3 ของ 10
อินพุตและเอาต์พุต
Input: ตัวเลข: 568 Output: Five Hundred And Sixty Eight
อัลกอริทึม
numToWord(num)
มีรายการบางอย่างที่เก็บคำสำหรับตัวเลขต่างๆ
Input: ตัวเลข
Output: แสดงตัวเลขเป็นคำ
Begin
if n >= 0 and n < 10, then
display units(n) เป็นคำ
else if n >= 10 and n < 20, then
display twoDigitNum(n) เป็นคำ
// คือสิบถึง十九
else if n >= 20 and n < 100, then
display tensMultiple(n/10) เป็นคำ
if n mod 10 ≠ 0, then
numToWord(n mod 10)
else if n >= 100 and n < 1000, then
display units(n/100) เป็นคำ
display "Hundred" เป็นคำ
// Hundred
if n mod 100 ≠ 0, then
display "And"
numToWord(n mod 100)
else if n >= 1000 and n <= 32767, then
numToWord(n/1000)
display "Thousand"
if n mod 1000 ≠ 0, then
numToWord(n mod 1000)
else
display invalid number and exit
End
ตัวอย่างโค้ด (C++)
#include <iostream>
using namespace std;
string getUnit(int n) {
// Return ตัวเลขหลักเดียวเป็นคำ
string unit[10] = {"Zero", "One","Two", "Three","Four","Five", "Six","Seven","Eight","Nine"};
return unit[n];
}
string getTwoDigits(int n) {
// n คือตัวเลข 2 หลัก
string td[10] = {"Ten", "Eleven","Twelve","Thirteen", "Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
return td[n%10];
}
string getTenMul(int n) {
// n คือพหุคูณของ 10
string tm[8] = {"Twenty", "Thirty","Fourty", "Fifty","Sixty", "Seventy","Eighty","Ninty"};
return tm[n-2];
}
string getTenPow(int pow) {
// กำลังของสิบเป็นคำ
string power[2] = {"Hundred", "Thousand"};
return power[pow-2];
}
void printNumToWord(int n) {
if (n >= 0 && n < 10)
cout << getUnit(n) << " "; // ค่า Unit เป็นคำ
else if (n >= 10 && n < 20)
cout << getTwoDigits(n) << " "; // จากสิบเอ็ดถึงสิบเก้า
else if (n >= 20 && n < 100) {
cout << getTenMul(n/10) << " ";
if (n%10 != 0)
printNumToWord(n%10); // เรียกซ้ำเพื่อแปลงตัวเลขเป็นคำ
} else if (n >= 100 && n < 1000) {
cout << getUnit(n/100) << " ";
cout << getTenPow(2) << " "; // Hundred
if (n%100 != 0) {
cout << "And ";
printNumToWord(n%100);
}
} else if (n >= 1000 && n <= 32767) {
printNumToWord(n/1000);
cout << getTenPow(3) << " "; // Thousand
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);
}
ผลลัพธ์
Enter a number between 0 to 32767: 568 Five Hundred And Sixty Eight