Short clean C++ code, with explanation

  • 11

    Function hundredStr() produces a string from integer less than 100.

    And in numberToWords() it uses a for loop to set "Thousand","Million","Billion".

    class Solution {
        string hundredStr(int num){
            vector<string> arr1={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
            vector<string> arr2={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
            string ret;
            ret=num%100<20?arr1[num%100]:arr2[(num%100)/10]+(num%10?" "+arr1[num%10]:"");
            if(num>99)ret=arr1[num/100]+" Hundred"+(num%100?" "+ret:"");
            return ret;
        string numberToWords(int num) {
            string ret;
            vector<string> strarr={"Thousand","Million","Billion"};
            for(int i=0;i<3;i++){
                ret=num%1000?hundredStr(num%1000)+" "+strarr[i]+" "+ ret:ret;
            while(ret.back()==' ')ret.pop_back();
            return ret.empty()?"Zero":ret;

  • 0

    Great code! It saves much work by considering 1-19 together instead of splitting it into 1-9 and 10-19 :-)

  • 0

    Thanks! It seems like I'm too lazy. XD

Log in to reply

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