Created
January 9, 2023 14:09
-
-
Save lazuee/f70f058242c58dae307a4966a69d0801 to your computer and use it in GitHub Desktop.
Number to Words in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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