Write C/C++/Java code to convert given number into words.
eg:- Input: 1234
Output: One thousand two hundred thirty-four.
Input: 10
Output: Ten
/* This Program will convert Numbers from -999,999,999 to 999,999,999 into words */
#include
#include
#include
#include
using namespace std;
const std::vector first14 = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen" };
const std::vector prefixes = { "twen", "thir", "for", "fif", "six", "seven", "eigh", "nine" };
std::string inttostr(const int number)
{
if (number < 0)
{
return "minus " + inttostr(-number);
}
if (number <= 14)
return first14.at(number);
if (number < 20)
return prefixes.at(number - 12) + "teen";
if (number < 100) {
unsigned int remainder = number - (static_cast(number / 10) * 10);
return prefixes.at(number / 10 - 2) + (0 != remainder ? "ty " + inttostr(remainder) : "ty");
}
if (number < 1000) {
unsigned int remainder = number - (static_cast(number / 100) * 100);
return first14.at(number / 100) + (0 != remainder ? " hundred " + inttostr(remainder) : " hundred");
}
if (number < 1000000) {
unsigned int thousands = static_cast(number / 1000);
unsigned int remainder = number - (thousands * 1000);
return inttostr(thousands) + (0 != remainder ? " thousand " + inttostr(remainder) : " thousand");
}
if (number < 1000000000) {
unsigned int millions = static_cast(number / 1000000);
unsigned int remainder = number - (millions * 1000000);
return inttostr(millions) + (0 != remainder ? " million " + inttostr(remainder) : " million");
}
throw std::out_of_range("inttostr() value too large");
}
int main()
{
int num;
cout << "Enter a number to convert it into letters : ";
cin >> num;
cout << endl << num << " = " << inttostr(num) << endl;
system("pause");
return 0;
}