My C++ solution accepted in 8ms


  • 0
    L
    class Solution {
    public:
        string numberToWords(int num) {
        	string di[9] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
        	string te[11] = {"Ten", "Eleven","Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
        	string tes[] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
        	string h[] = { "","Hundred", "Thousand", "Million", "Billion" };
        	int div[] = { 100, 10, 1000, 1000 };
        
        	int i = 0;
        	string str;
        	if (num == 0)
        		return "Zero";
        	while (num != 0){
        		int a = num%div[i];
        		num = num / div[i];
        		i++;
        		int b = 0;
        		if (a >= 100){
        			b = a / 100;
        			a = a % 100;
        		}
        		if (a == 0){
        			if (b != 0)
        				str = di[b - 1] +" "+ h[1] + " "+h[i - 1] +" "+str;
        			continue;
        		}
        		if (a<10)
        			str = di[a - 1] +" "+ h[i - 1]+" " + str;
        		else if (a<20)
        			str = te[a - 10] + " " + h[i - 1] + " " + str;
        		else{
        			if (a % 10 == 0)
        				str = tes[a / 10 - 2] + " " + h[i - 1] + " " + str;
        			else
        				str = tes[a / 10 - 2] + " " + di[a % 10 - 1] + " " + h[i - 1] + " " + str;
        		}
        		if (b != 0)
        			str = di[b - 1] + " " + h[1] + " " + str;
        	}
        	while(str[str.length()-1]==' ')
        	    str.pop_back();
        	return str;
        }
    };

Log in to reply
 

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