Not clean but easy to understand (C++


  • 0
    D
    class Solution {
    public:
    string numberToWords(int num) {
        string unit[4]={""," Thousand "," Million "," Billion "};
        string number[20]={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
        
        string number100[10]={"","One Hundred ","Two Hundred ","Three Hundred ","Four Hundred ","Five Hundred ","Six Hundred ","Seven Hundred ","Eight Hundred ","Nine Hundred "};
        
        string number10[10]={"","","Twenty ","Thirty ","Forty ","Fifty ","Sixty ","Seventy ","Eighty ","Ninety "};
        
        int num_1;
        int num_10;
        int num_100;
        
        int unit_cnt=0;
        int div;
        string result="";
        string number_part;
        
        if(num==0)
            return "Zero";
        while(num)
            {
            div=num%1000;
            if(div==0)
                {
                    num/=1000;
                    unit_cnt++;
                    continue;
                }
                
            num_1=div%10;
            div/=10;
            num_10=div%10;
            div/=10;
            num_100=div%10;
    
            if((num_10*10+num_1)<20)
                number_part=number100[num_100]+number[(num_10*10+num_1)];
            else
                number_part=number100[num_100]+number10[num_10]+number[num_1];
            number_part.erase(number_part.find_last_not_of(" ")+1);    
            result=number_part+unit[unit_cnt]+result;
            
            num/=1000;
            unit_cnt++;
            }
            return result.erase(result.find_last_not_of(" ")+1);;
    }
    

    };


Log in to reply
 

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