I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
Convert a non-negative integer to its English words representation. Given input is guaranteed to be less than
2^31 - 1
.
Inputs
123
1234567891
151
1414312
1234
1241234113
Outputs
"One Hundred Twenty Three"
"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
"One Hundred Fifty One"
"One Million Four Hundred Fourteen Thousand Three Hundred Twelve"
"One Thousand Two Hundred Thirty Four"
"One Billion Two Hundred Forty One Million Two Hundred Thirty Four Thousand One Hundred Thirteen"
Code
#include <string>
class Solution {
std::string zero_to_twenty[20] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
std::string tens_and_zero[10] = {"Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
std::string SPACE = " ";
std::string BILLION = "Billion";
std::string MILLION = "Million";
std::string THOUSAND = "Thousand";
std::string HUNDRED = "Hundred";
std::string ZERO = "Zero";
std::string EMPTY_STRING = "";
static inline constexpr int one_billion = 1e9;
static inline constexpr int one_million = 1e6;
static inline constexpr int one_thousand = 1e3;
static inline constexpr int one_hundred = 100;
static inline constexpr int twenty = 20;
static inline constexpr int ten = 10;
public:
inline std::string numberToWords(int num) {
if (num == 0) {
return ZERO;
} else {
std::string words = int2string(num);
return words.substr(1, words.length() - 1);
}
}
private:
inline std::string int2string(const int n) {
if (n >= one_billion) {
return int2string(n / one_billion) + SPACE + BILLION + int2string(n % one_billion);
} else if (n >= one_million) {
return int2string(n / one_million) + SPACE + MILLION + int2string(n % one_million);
} else if (n >= one_thousand) {
return int2string(n / one_thousand) + SPACE + THOUSAND + int2string(n % one_thousand);
} else if (n >= one_hundred) {
return int2string(n / one_hundred) + SPACE + HUNDRED + int2string(n % one_hundred);
} else if (n >= twenty) {
return SPACE + tens_and_zero[n / ten] + int2string(n % ten);
} else if (n >= 1) {
return SPACE + zero_to_twenty[n];
} else {
return EMPTY_STRING;
}
}
};