class Solution {
public:
std::vector<string> levels = {"Thousand", "Million","Billion"};
vector<string> nums1 = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten", "Eleven", "Twelve", "Thirteen", "Forteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> nums2 = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string numberToWords(int num) {
string res = "";
if(num == 0){
return "Zero";
}
int level = 0;
while(num > 0){
int cur = num % 1000;
string tmp = "";
if(cur > 0){
int lower = cur % 100;
if(cur / 100 > 0){
tmp = nums1[cur / 100 - 1] + " Hundred" + " ";
}
if(lower != 0){
if(lower < 20){
tmp += nums1[lower - 1] + " ";
}
else{
int digit1 = lower % 10;
tmp += nums2[lower / 10 - 2] + " ";
if(digit1 != 0){
tmp += nums1[digit1 - 1] + " ";
}
}
}
}
if(tmp != "" && level > 0){
tmp += levels[level - 1] + " ";
}
res = tmp + res;
num /= 1000;
level++;
}
res.pop_back();
return res;
}
};
class Solution {
public:
string numberToWords(int num) {
string res = convertHundred(num % 1000);
vector<string> v = {"Thousand", "Million", "Billion"};
for (int i = 0; i < 3; ++i) {
num /= 1000;
res = num % 1000 ? convertHundred(num % 1000) + " " + v[i] + " " + res : res;
}
while (res.back() == ' ') res.pop_back();
return res.empty() ? "Zero" : res;
}
string convertHundred(int num) {
vector<string> v1 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> v2 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string res;
int a = num / 100, b = num % 100, c = num % 10;
res = b < 20 ? v1[b] : v2[b / 10] + (c ? " " + v1[c] : "");
if (a > 0) res = v1[a] + " Hundred" + (b ? " " + res : "");
return res;
}
};
Comments
Post a Comment