Skip to content

Instantly share code, notes, and snippets.

@ashafq
Last active November 9, 2023 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashafq/3ca52f5848fc2613a9e87e913725f72d to your computer and use it in GitHub Desktop.
Save ashafq/3ca52f5848fc2613a9e87e913725f72d to your computer and use it in GitHub Desktop.
/**
* Integer to Cardinal converter (unsigned)
*
* Copyright (C) 2021 Ayan Shafqat <ayan.x.shafqat@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#include <array>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
namespace {
std::string cardinal(long num) {
static const std::array<std::string, 20> unit{
{"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "tweleve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}};
static const std::array<std::string, 10> ten{{"", "ten", "twenty", "thirty",
"fourty", "fifty", "sixty",
"seventy", "eighty", "ninety"}};
static const std::array<std::string, 8> weight{
{"", "thousand", "million", "billion", "trillion", "quadrillion",
"quintillion"}};
std::string res{};
if (num >= 1000) {
auto ex =
static_cast<long>(floor(log10(num))) / 3; // Get engineering exponent
auto val = static_cast<long>(pow(10, ex * 3)); // Get value
auto msd = num / val;
auto rem = num % val;
res += cardinal(msd);
res += " ";
res += weight[ex];
res += rem ? (" " + cardinal(rem)) : "";
} else if (num >= 100) {
auto msd = num / 100;
auto rem = num % 100;
res += cardinal(msd) + " hundred";
res += rem ? (" " + cardinal(rem)) : "";
} else if (num >= 20) {
auto rem = num % 10;
res += ten[num / 10];
if (rem != 0) {
res += "-";
res += unit[rem];
}
} else {
res += unit[num];
}
return res;
}
} // namespace
int main() {
std::cout << "Enter an integer to convert it into words (e.g. 256 -> two hundred fifty-six)" << std::endl;
do {
std::string line{};
std::getline(std::cin, line);
long num{0};
std::stringstream ss{line};
if (!(ss >> num))
break;
std::cout << num << " -> " << cardinal(num) << std::endl;
} while (true);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment