2024-08-07 Daily Challenge
Today I have done leetcode's August LeetCoding Challenge with cpp
.
August LeetCoding Challenge 7
Description
Integer to English Words
Convert a non-negative integer num
to its English words representation.
Example 1:
Input: num = 123 Output: "One Hundred Twenty Three"
Example 2:
Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Constraints:
0 <= num <= 231 - 1
Solution
class Solution {
const string ZERO = "Zero";
const vector<pair<int, string>> units = {
{ 1000000000, "Billion" },
{ 1000000, "Million" },
{ 1000, "Thousand" },
{ 1, "" }
};
vector<string> ge20 = {
"", // 0
"", // 10
"Twenty",
"Thirty",
"Forty",
"Fifty",
"Sixty",
"Seventy",
"Eighty",
"Ninety"
};
vector<string> lt20 = {
"",
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen",
};
string numberLT1000ToWords(int num) {
string result;
if (num >= 100) {
result += lt20[num / 100] + " Hundred";
if (num % 100 == 0) return result;
result += " ";
num %= 100;
}
if (!num) return result;
if (num < 20) {
result += lt20[num];
} else {
result += ge20[num/10];
if (num % 10) result += " " + lt20[num % 10];
}
return result;
}
void numberPartToWords(string &result, int &num, const int threshold, const string &unit) {
if (num >= threshold) {
if (result.length()) result += " ";
result += numberLT1000ToWords(num / threshold);
if (unit.length()) result += " " + unit;
num %= threshold;
}
}
public:
string numberToWords(int num) {
if (!num) return move(ZERO);
string answer = "";
for (const auto &[threshold, unit]: units) {
numberPartToWords(answer, num, threshold, unit);
}
return answer;
}
};