이 알고리즘은 주어진 숫자를 영어 단어로 변환합니다. 564처럼 오백육십사(Five Hundred and Sixty-Four)가 됩니다.
이 알고리즘의 경우 사전 정의된 일부 문자열이 제공되며 해당 목록에서 단어로 만들 적절한 단어를 가져옵니다.
목록은 다음과 같습니다.
- 단위: Zero, One…Nine과 같이 (0에서 9까지)에 대한 모든 단어를 보유합니다.
- 두자리: Ten, eleven…
- tenMul: 10배의 경우 (20-90), 예를 들어 Twenty, Thirty, ... Ninety.
- 텐파워: 10의 2와 3의 거듭제곱으로 100,000에 대한 것입니다.
입력 및 출력
Input: The number: 568 Output: Five Hundred And Sixty Eight
알고리즘
numToWord(num)
다른 정수에 대한 단어를 보유하는 일부 목록이 있습니다.
입력: 번호입니다.
출력: 숫자를 단어로 표현하세요.
Begin if n >= 0 and n < 10, then display units(n) into words else if n >= 10 and n < 20, then display twoDigitNum(n) into words //It is from ten to nineteen else if n >= 20 and n <100, then display tensMultiple(n/10), into words if n mod 10 ≠ 0, then numToWord(n mod 10) else if n >= 100 and n < 1000, then display units(n/100), into words display “Hundred”, into words //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
예시
#include<iostream>
using namespace std;
string getUnit(int n) {
//Return single digit to word
string unit[10] = {"Zero", "One","Two", "Three","Four","Five", "Six","Seven","Eight","Nine"};
return unit[n];
}
string getTwoDigits(int n) {
//Here n is 2 digit number
string td[10] = {"Ten", "Eleven","Twelve","Thirteen", "Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
return td[n%10];
}
string getTenMul(int n) {
//Here n is multiple of 10
string tm[8] = {"Twenty", "Thirty","Fourty", "Fifty","Sixty", "Seventy","Eighty","Ninty"};
return tm[n-2];
}
string getTenPow(int pow) {
//The power of ten in words
string power[2] = {"Hundred", "Thousand"};
return power[pow-2];
}
void printNumToWord(int n) {
if(n >= 0 && n < 10)
cout << getUnit(n) << " "; //Unit values to word
else if(n >= 10 && n < 20)
cout << getTwoDigits(n) << " "; //from eleven to nineteen
else if(n >= 20 && n < 100) {
cout << getTenMul(n/10)<<" ";
if(n%10 != 0)
printNumToWord(n%10); //Recursive call to convert num to word
}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);
} 출력
Enter a number between 0 to 32767: 568 Five Hundred And Sixty Eight