Skip to content

Instantly share code, notes, and snippets.

@lazuee
Created January 9, 2023 14:09
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 lazuee/f70f058242c58dae307a4966a69d0801 to your computer and use it in GitHub Desktop.
Save lazuee/f70f058242c58dae307a4966a69d0801 to your computer and use it in GitHub Desktop.
Number to Words in C++
#include <iostream>
#include <string>
std::string number_to_words(int num) {
if (num == 0) {
return "zero";
}
if (num < 0) {
return "minus " + number_to_words(-num);
}
std::string words;
if (num >= 1000000000) {
words += number_to_words(num / 1000000000) + " billion ";
num %= 1000000000;
}
if (num >= 1000000) {
words += number_to_words(num / 1000000) + " million ";
num %= 1000000;
}
if (num >= 1000) {
words += number_to_words(num / 1000) + " thousand ";
num %= 1000;
}
if (num >= 100) {
words += number_to_words(num / 100) + " hundred ";
num %= 100;
}
if (num >= 20) {
static const std::string tens[] = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
words += tens[num / 10] + " ";
num %= 10;
}
static const std::string digits[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
words += digits[num];
return words;
}
int main() {
std::cout << number_to_words(30) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment