c++ 3ms solution

• ``````class Solution {
vector<string> Bigunits = {"Hundred","Thousand","Million","Billion"};
vector<string> MidUnits = {"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
vector<string> MidSUnits = {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
vector<string> SmallUnits = {"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};

string& trim_right_inplace(string& s,const std::string& delimiters = " \f\n\r\t\v" ){
return s.erase( s.find_last_not_of( delimiters ) + 1 );
}

string ForThousand(int num){
string res = "";
int hund = 0;
if (num>99){
hund = num/100;
num = num%100;
}

if (num>9){
num = num%10;
}

res = (hund>0?(SmallUnits[hund]+" "+Bigunits[0]+" "):"");

res += MidSUnits[num];
else
//Trim end space
return trim_right_inplace(res);

}

public:
string numberToWords(int num) {
//find if there is any billion
if (num == 0) return "Zero";
int bill = 0;
int mill = 0;
int thou = 0;
if (num>(1000000000-1)){
bill = num/1000000000;
num = num%1000000000;
}

if (num>(1000000-1)){
mill = num/1000000;
num = num%1000000;
}

if (num>(1000-1)){
thou = num/1000;
num = num%1000;
}

string res="";

if (bill>0)
res+=ForThousand(bill)+" "+Bigunits[3]+" ";

if (mill>0)
res+=ForThousand(mill)+" "+Bigunits[2]+" ";

if (thou>0)
res+=ForThousand(thou)+" "+Bigunits[1] + " ";

if (num>0)
res+=ForThousand(num);
return trim_right_inplace(res);
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.