A C++ solution, 8ms


  • 0
    P
    class Solution {
    public:
        public:
    	//2,147,483,647
    	string numberToWords(int num) 
    	{
    		if(num==0)
    			return "Zero";
    		string strRet;
    		int arrK[4];
    		string arrStrK[4];
    
    		for(int i=0; i<4; i++)
    		{
    			arrK[i] = num%1000;
    			num /= 1000;
    		}
    		for(int i=0; i<4; i++)
    		{
    			char tmp[10] = {0};
    
    			if(arrK[i]<10)
    				sprintf(tmp, "00%d", arrK[i]);
    			else if(arrK[i]<100)
    				sprintf(tmp, "0%d", arrK[i]);
    			else
    				sprintf(tmp, "%d", arrK[i]);
    			arrStrK[i] = tmp;
    		}
    
    		if(0 != arrStrK[3].compare("000"))
    		{
    			strRet += fun(arrStrK[3]);
    			strRet += "Billion ";
    		}
    		if(0 != arrStrK[2].compare("000"))
    		{
    			strRet += fun(arrStrK[2]);
    			strRet += "Million ";
    		}
    		if(0 != arrStrK[1].compare("000"))
    		{
    			strRet += fun(arrStrK[1]);
    			strRet += "Thousand ";
    		}
    		if(0 != arrStrK[0].compare("000"))
    		{
    			strRet += fun(arrStrK[0]);
    		}
    
    		if(!strRet.empty() && strRet.back() == ' ')
    			strRet.erase(strRet.end()-1);
    
    		return strRet;
    	}
    
    	string fun(string strNum)//0 <= num <=999
    	{
    		string strRet;
    		if(strNum.compare("000")==0)
    			return strRet;
    
    		string arr3[10] = {"", "One Hundred", "Two Hundred", "Three Hundred", "Four Hundred", "Five Hundred", 
    			"Six Hundred", "Seven Hundred", "Eight Hundred", "Nine Hundred"};
    		string arr2[10] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    		string arr21[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", 
    		    "Seventeen", "Eighteen", "Nineteen"};
    		string arr1[10] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    
    		int a3, a2, a1;
    		a3 = strNum[0]-'0';
    		a2 = strNum[1]-'0';
    		a1 = strNum[2]-'0';
    
    		strRet += arr3[a3];
    		if(!arr3[a3].empty()) strRet += " ";
    		if(a2 != 1)
    		{
    			strRet += arr2[a2];
    			if(!arr2[a2].empty()) strRet += " ";
    			strRet += arr1[a1];
    			if(!arr1[a1].empty()) strRet += " ";
    		}
    		else
    		{
    			strRet += arr21[a1];
    			if(!arr21[a1].empty()) strRet += " ";
    		}
    
    		//printf("num:%s, English:%s#\n", strNum.c_str(), strRet.c_str());
    
    		return strRet;
    	}
    };

Log in to reply
 

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