Skip to content

Instantly share code, notes, and snippets.

@dyigitpolat
Created April 12, 2022 15:08
Show Gist options
  • Save dyigitpolat/128d482aeae9dbc349d754de6e70cc8e to your computer and use it in GitHub Desktop.
Save dyigitpolat/128d482aeae9dbc349d754de6e70cc8e to your computer and use it in GitHub Desktop.
convert integers to english.
#include <iostream>
#include <string>
#include <array>
std::array<std::string, 10> figures{
"",
"One ",
"Two ",
"Three ",
"Four ",
"Five ",
"Six ",
"Seven ",
"Eight ",
"Nine "
};
std::array<std::string, 10> teens{
"Ten ",
"Eleven ",
"Twelve ",
"Thirteen ",
"Fourteen ",
"Fifteen ",
"Sixteen ",
"Seventeen ",
"Eighteen ",
"Nineteen "
};
std::array<std::string, 10> tens{
"",
"",
"Twenty ",
"Thirty ",
"Forty ",
"Fifty ",
"Sixty ",
"Seventy ",
"Eighty ",
"Ninety "
};
std::array<std::string, 4> thousands{
"",
"Thousand ",
"Million ",
"Billion "
};
std::string convert_hundred(long number)
{
if(number < 10) return figures[number];
if(number < 20) return teens[number - 10];
return
tens[number / 10] +
figures[number % 10];
}
std::string convert_thousand(long number)
{
if(number < 100)
return convert_hundred(number % 100);
return
figures[number / 100] + "Hundred " +
convert_hundred(number % 100);
}
std::string convert(std::string number_str)
{
int length = number_str.size();
int thousands_idx = length / 3;
long number = std::atol(number_str.c_str());
if(number == 0) return "Zero";
std::string result{};
int idx{};
while(number)
{
std::string current_thousand{
convert_thousand(number % 1000)
};
bool empty {current_thousand.size() == 0};
result =
current_thousand +
(empty ? "" : thousands[idx]) +
result;
number /= 1000;
idx++;
}
result.pop_back();
return result;
}
int main()
{
std::cout << convert("1") << "\n";
std::cout << convert("2") << "\n";
std::cout << convert("0") << "\n";
std::cout << convert("14") << "\n";
std::cout << convert("17") << "\n";
std::cout << convert("173") << "\n";
std::cout << convert("273") << "\n";
std::cout << convert("1234") << "\n";
std::cout << convert("12345") << "\n";
std::cout << convert("1000000001") << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment