首页 > 试题广场 >

数字发音

[编程题]数字发音
  • 热度指数:5210 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个非负整数x,请编写一个算法返回一个string,代表该整数的英文描述。

测试样例:
1234
返回:"One Thousand,Two Hundred Thirty Four"
       private  string[] belowTen = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};  
    private  string[] belowTwenty = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};  
    private  string[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};  
  
    public string toString(int x)
    {
        if (x == 0) return "Zero";  
        return helper(x);   
    }  
  
    private String helper(int num) {  
        string result = "";
        if (num < 10) result = belowTen[num];
        else if (num < 20) result = belowTwenty[num - 10];
        else if (num < 100) result = belowHundred[num / 10] + " " + helper(num % 10);
        else if (num < 1000) result = helper(num / 100) + " Hundred " + helper(num % 100);
        else if (num < 1000000) result = helper(num / 1000) + " Thousand" +( num % 1000 > 0 ? "," : " ") + helper(num % 1000);
        else if (num < 1000000000) result = helper(num / 1000000) + " Million" + (num % 1000000 > 0 ? "," : " ") + helper(num % 1000000);
        else result = helper(num / 1000000000) + " Billion " + helper(num % 1000000000);
        return result.Trim(' '); 
    }  

发表于 2016-03-19 07:17:32 回复(0)

python solution

class ToString:
    def toString(self, num):

        to19='One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
        tens="Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety".split()
        def words(n):
            if n<20:return to19[n-1:n]
            if n<100:return [tens[n//10-2]]+words(n%10)
            if n<1000:
                return [to19[n//100-1]]+["Hundred"]+words(n%100)
            for p,w in enumerate(('Thousand',"Million","Billion"),1):
                if n<1000**(p+1):
                    return words(n//1000**p)+[w]+words(n%1000**p)
        return " ".join(words(num)).replace("Thousand ","Thousand,").replace("lion ","lion,") or "Zero"
发表于 2017-10-31 17:01:07 回复(0)
class ToString {
public:     string a[10] = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};     string b[10] = {"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};     string c[10] = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};     string F(int n){         string r;         if(n<10)             r = a[n];         else if(n<20)                 r = b[n-10];         else if(n<100)             r = c[n/10]+" "+F(n%10);         else if(n<1000)             r = F(n/100)+" Hundred "+F(n%100);         else if(n<1000000)             r = F(n/1000)+" Thousand"+(n%1000>0?",":" ")+F(n%1000);         else if(n<1000000000)             r = F(n/1000000)+" Million"+(n%1000000>0?",":" ")+F(n%1000000);         else             r = F(n/1000000000)+" Billion "+F(n%1000000000);         int l = r.length();         if(r[l-1]==' ')             r = r.substr(0,l-1);         return r;     }
    string toString(int x) {
        if(x==0)
            return "Zero";
        return F(x);
    }
};

发表于 2019-03-18 02:21:44 回复(0)
vector<string> digits = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
vector<string> teens = { "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
vector<string> tens = { "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
vector<string> bigs = { "", "Thousand", "Million" };

class ToString {
public:
	string numToString100(int number)
	{
		string str = "";

		/*转换百位数的地方*/
		if (number >= 100){
			str += digits[number / 100 - 1] + " Hundred ";
			number %= 100;
		}

		//转换十位数的地方
		if (number >= 11 && number <= 19)
		{
			return str += teens[number - 11]+" ";
		}
		else if (number == 10 || number >= 20)
		{
			str += tens[number / 10 - 1] + " ";
			number %= 10;
		}

		//转换个位的地方
		if (number >= 1 && number <= 9)
		{
			str += digits[number - 1]+" ";
		}
		return str;

	}

    void removeLastSpace(string &str)
    {
        if(str[str.length()-1]==' ')
            str.erase(str.length()-1,str.length());
    }
	string toString(int x) {
		// write code here
		if (x == 0)
			return "zero";
		else if (x < 0)
			return "Negative" + toString(abs(x));

		int count = 0;
		string str = "";

		while (x > 0)
		{
            //这句话很关键,处理1000的发音
            //前面+一个函数处理100以下的数字发音
			if (x % 1000 != 0)
			{
				if (str != "")
					str = numToString100(x % 1000) + bigs[count] + "," + str;
				else
					str = numToString100(x % 1000)+ bigs[count];
			}
			x /= 1000;
			count++;
		}
            removeLastSpace(str);
		return str;
	}
};


发表于 2017-05-19 09:23:36 回复(0)
map<string, string> fx{
    {"0", "Zero"}, {"1", "One"}, {"2", "Two"}, {"3", "Three"}, {"4", "Four"},
    {"5", "Five"}, {"6", "Six"}, {"7", "Seven"}, {"8", "Eight"}, {"9", "Nine"}
};
map<string, string> f1x{
    {"10", "Ten"}, {"11", "Eleven"}, {"12", "Twelve"}, {"13", "Thirteen"}, {"14", "Fourteen"},
    {"15", "Fifteen"}, {"16", "Sixteeen"}, {"17", "Seventeen"}, {"18", "Eighteen"}, {"19", "Nineteen"}
};
map<string, string> fx0{
    {"10", "Ten"}, {"20", "Twenty"}, {"30", "Thirty"}, {"40", "Forty"}, {"50", "Fifty"},
    {"60", "Sixty"}, {"70", "Seventy"}, {"80", "Eighty"}, {"90", "Ninety"}
};
map<string, string> f00{
    {"0", ""}, {"2", "Hundred"}, {"3", "Thousand"}, {"6", "Million"}, {"9", "Billion"}
};
string deletepre(string x){
    // 去除前导0
    int i = 0;
    while(i<x.size() && x[i]=='0') i++;
    return x.substr(i);
};
string decode3b(string x){
    x = deletepre(x);
    string res = "";
    if(x.length()==3){
        string tmp = fx[x.substr(0,1)]+" "+f00["2"];
        res += tmp;
        x = x.substr(1);
        x = deletepre(x);
        if(x!="") res += " ";
    }
    if(x.length()==2){
        if(x[0]=='1'){
            res += f1x[x];
            x = "";
        }else{
            if(x[1]=='0'){
                res += fx0[x];
                x = "";
            }else{
                res += (fx0[string(1, x[0])+"0"]);
                x = x.substr(1);
                x = deletepre(x);
                if(x!="") res += " ";
            }
        }
    }
    res += fx[x];
    return res;
}
class ToString {
public:
    string toString(int x) {
        // write code here
        if(x==0) return "zero";
        string str = to_string(x);
        string res = "";
        int n = str.length();
        int j = max(0, n-3);
        int n0 = 0;
        while(str.length()>0){
            string tmp = str.substr(j);
            str = str.substr(0, j);
           
            tmp = deletepre(tmp);
            if(tmp!="")
                res = decode3b(tmp)+" "+f00[to_string(n0)]+","+res;
            j = max(0, j-3);
            n0 += 3;
        }
        if(res[res.length()-1]==',')
            res = res.substr(0, res.length()-1);
        if(res[res.length()-1]==' ')
            res = res.substr(0, res.length()-1);
        return res;
    }
};
发表于 2019-02-23 19:36:25 回复(0)
string digit[10]{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
string tens[]{"","","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
string tenMore[10]{"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
class ToString {
public:
    string toHundred(string s)
{
	string res = "";
	if (s.size() == 3)
	{
		if(s[0] != '0') res += digit[s[0] - '0'] + " Hundred ";
		if (s[1] == '0')
		{
			if (s[2] == '0') return res;
			res += digit[s[2] - '0'] + " ";
		}
		else if (s[1] == '1')
		{
			res += tenMore[stoi(s.substr(1)) - 10] + " ";
		}
		else
		{
			res += tens[s[1] - '0'] + " ";
			if(s[2] != '0') res += digit[s[2] - '0'] + " ";
		}
	}
	else if (s.size() == 2)
	{
		if (s[0] == '1')
		{
			res += tenMore[stoi(s) - 10] + " ";
		}
		else
		{
			res += tens[s[0] - '0'] + " ";
			if(s[1] != '0') res += digit[s[1] - '0'] + " ";
		}
	}
	else
	{
		res += digit[s[0] - '0'] + " ";
	}

	return res;
}

string toString(int x)
{
	string s = to_string(x), res = "";
	int idx = 0;
	if (s.size() >= 10)
	{
		res += digit[s[idx] - '0'] + " Billion,";
		++idx;
	}
	if (s.size() >= 7)
	{
		string cur = toHundred(s.substr(idx, s.size() - 6 - idx));
		if(cur != "") res +=  cur + "Million,";
		idx = s.size() - 6;
	}
	if (s.size() >= 4)
	{
		string cur = toHundred(s.substr(idx, s.size() - 3 - idx));
		if (cur != "") res += cur + "Thousand,";
		idx = s.size() - 3;
	}
	res += toHundred(s.substr(idx));

	return res.substr(0,res.size() - 1);
}
};

发表于 2017-07-01 15:31:53 回复(0)
唉,调格式挺费劲。。。

import java.util.*;

public class ToString {
    String[] baseNum = { "Zero", "One", "Two", "Three", "Four", "Five", "Six",
			"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
			"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
			"Nineteen", };
	String[] tyNum = { "","Twenty", "Thirty", "Forty", "Fifty", "Sixty",
			"Seventy", "Eighty", "Ninety" };
	String[] bigNum = { "", "Thousand", "Million", "Billion" };

	public String toString(int x) {

		StringBuffer sb = null;
		int temp, j = 0;
		if (x == 0)
			return baseNum[0];
		while (x != 0) {
			temp = x % 1000;
			if (temp != 0) {
				if (sb == null) {
					sb = tempToString(temp).append(" "+bigNum[j]);
				} else {
					sb = tempToString(temp).append(" " + bigNum[j] + "," + sb);
				}
			}
			j++;
			x /= 1000;
		}
		return sb.toString().trim();
	}

	// 将三位数转为字符串
	public StringBuffer tempToString(int str) {
		StringBuffer newsb = new StringBuffer();
		int i = str / 100;
		if (i != 0)
			newsb = newsb.append(baseNum[i] + " Hundred ");
		i = str % 100;
		if (i > 0 && i <= 19)
			newsb = newsb.append(baseNum[i]);
		else if(i != 0){
			newsb = newsb.append(tyNum[i / 10 - 1]);
			if (i % 10 != 0)
				newsb.append(" " + baseNum[i % 10]);
		}
		return newsb;
	}
}

发表于 2017-06-28 17:41:12 回复(0)
class ToString:
    def toString(self, x):
        i, s = 0, []
        while x > 0:
            d = []
            t = x % 1000  # 百十个位
            y = t / 100  # 百
            if y > 0:
                d.append(self.B[y] + ' ' + self.A[0])
            z = t % 100  # 个十
            if z > 0:
                if z < 20:
                    d.append(self.B[z])
                else:
                    d.append(self.C[z / 10 - 2])  # 十
                    y = z % 10  # 个
                    if y > 0:
                        d.append(self.B[y])
                if i > 0:
                    d.append(self.A[i])
                s.insert(0, ' '.join(d))
            i += 1
            x /= 1000

        return ','.join(s)

    A = ['Hundred', 'Thousand', 'Million', 'Billion']
    B = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve',
         'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seveteen', 'Eighteen', 'Nineteen']
    C = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']

发表于 2017-03-11 19:48:29 回复(0)
//巧妙的用空串填充占位
        string base[20] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
                           "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
                            "Eighteen", "Nineteen"};  //0~19
        string tyNum[10] = {"","","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty","Ninety"};
        string bigNum[4] = {"", "Thousand", "Million", "Billion"};
        string res;
        int k=0;
        //将x每3位数分成一组进行编码
        while(x>0){
            int val = x%1000;
            //对每3位数进行编码
            string temp;
            if(base[val/100]!=""){
                temp+=base[val/100];
                temp+=" Hundred";
            }
            if(val%100<20){  //小于20的数单独编码
                if(!temp.empty())temp+=" ";
                temp+=base[val%100];
            }else{
                if(!temp.empty())temp+=" ";
                temp+=tyNum[val%100/10];
                if(base[val%10]!=""){
                    if(!temp.empty())temp+=" ";
                    temp+=base[val%10];
                }
            }
            if(!temp.empty()&&bigNum[k]!=""){
                temp+=" ";
                temp+=bigNum[k];
                if(!res.empty())temp+=",";
            }
            res = temp+res;
            k++;
            x /= 1000;
        }
        return res;

编辑于 2016-07-05 21:05:42 回复(0)
Solution: 提供一个Java版的可以submit success的版本。

public class ToString {
     String[] dig = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
   	 String[] tee = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
     String[] ten = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
     String[] big = {"", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Sextillion", "Septillion", "Octillion", "Nonillion"};  
 
    public String toString(int x) {
        if (x == 0) {     // special cases    
            return "Zero";
        }else if(x<0){
        	return "Negative" + toString(-1*x);
        }
        
        int count=0;
        String str="";
        while(x>0){
            if(x%1000!=0){
                //这句是最重要的一句,1000的发音就在这里处理。  
                //前面+一个函数处理100一下的数字  
                //利用字符串数组bigs轻松处理每个1000的发音  
                //而且巧妙地在第一个位置加上逗号","。  
                //str = numUnder100(x % 1000) + big[count] + "," + str;  
                if(str!=""){ // 1234 ==> One Thousand,Two Hundred Thirty Four
	            str = numUnder100(x % 1000) + big[count] + "," + str;  
		    }else{
		    str = numUnder100(x % 1000) + big[count];
	           }
              }
        	
            x/=1000;
            count++;
        }        
        return str.trim(); //remove the last " "(space)
    }   
    
    // 将三位数转换为string
    public String numUnder100(int num) {
        String str="";
         //100以下的数字需要四种情况处理,十分麻烦。  
	    if (num >= 100){  
	        str += dig[num/100-1] + " Hundred ";  
	        num %= 100;  
	    }
        
	    if (num >= 11 && num <= 19){  
	        return str + tee[num - 11] + " ";  
	    }  
	    
        if (num == 10 || num >= 20){  
	        str += ten[num/10 - 1] + " ";  
	        num %= 10;  
	 }
        
        if (num >= 1 && num <= 9){  
	        str += dig[num - 1] + " ";  
	}
        
        return str;  
    }
}

编辑于 2016-01-05 09:38:10 回复(1)

# -*- coding:utf-8 -*-

def helper(x):
    below20 = ['', 'One', 'Two', 'Three', 'Four', 
               'Five', 'Six', 'Seven', 'Eight', 'Nine'
              'Ten', 'Eleven', '"Twelve", "Thirteen", "Fourteen", 
               "Fifteen", "Sixteen", "Seventeen", "Eighteen"]
    below100 = ["", "", "Twenty", "Thirty", "Fourty", 
                "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
    
    if x<20:
        return below20[x]
    elif x<100:
        if x%10:
            return below100[x//10] + ' ' + helper(x%10)
        else:
            return below100[x//10]
    elif x<1000:
        if x%100:
            return below20[x//100] + ' Hundrend ' +  helper(x%100)
        else:
            return below20[x//100] + ' Hundrend'
class ToString:    
    def toString(self, num):   
        r = []
        count = 0
        t = ['Thounsand', 'Million', 'Billion']
        while (num>0):
            if num <1000:
                r.append(helper(num))
            else:
                r.append(helper(num%1000))
            
            num = num // 1000
            if num >0 :
                count = count + 1
        #r = r[::-1]
        if count == 0:
                return ''.join(r)
        for i in range(count):
            r[i+1] =  r[i+1] + ' ' + t[i]
        
        return ','.join(r[::-1])

编辑于 2020-02-20 18:43:08 回复(0)

思路

1.每三个数字分一组,组成“X Hundred Y Z”这样的字串,根据位增加“Thousand”等
2.从后往前遍历,每次读取三个字符,处理后子串入栈
3.返回栈中字符串的和

重点

1.如何增加空格如何增加逗号
2.区分10-19和其他

class ToString {
public:
    string toString(int x) {
        // write code here
        string uni[10] = { "","One","Two", "Three","Four","Five" ,"Six", "Seven","Eight","Nine" };
        string dec1[10] = { "Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen" };
        string dec[10] = { "","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety" };

        queue<int> a;
        stack<string> s;

        int xx = x;


        while (xx)
        {
            a.push(xx % 10);
            xx /= 10;
        }

        int count = 0;
        while (!a.empty())
        {
            int flag = 0;
            int dcd = 0;
            string temp;
            if (a.size() >= 3)
            {
                int h, d, u;

                u = a.front();
                a.pop();
                d = a.front();
                a.pop();
                h = a.front();
                a.pop();

                if (h)
                {
                    temp += uni[h];
                    temp += " Hundred";
                    flag++;
                }

                if (d == 1)
                {
                    if (flag)
                    {
                        temp += " ";
                    }
                    temp += dec1[u];
                    flag++;
                    dcd++;
                }
                else
                {
                    if (d)
                    {
                        if (flag)
                        {
                            temp += " ";
                        }
                        temp += dec[d];
                        flag++;
                    }

                }

                if (u && !dcd)
                {
                    if (flag)
                    {
                        temp += " ";
                    }
                    temp += uni[u];
                    flag++;
                }

            }
            else if (a.size() == 2)
            {
                int d, u;

                u = a.front();
                a.pop();
                d = a.front();
                a.pop();

                if (d == 1)
                {
                    temp += dec1[u];
                    flag++;
                    dcd++;
                }
                else
                {
                    if (d)
                    {
                        temp += dec[d];
                        flag++;
                    }
                }

                if (u && !dcd)
                {
                    if (flag)
                    {
                        temp += " ";
                    }
                    temp += uni[u];
                    flag++;
                }


            }
            else
            {
                int u = a.front();
                a.pop();

                temp += uni[u];
                flag++;
            }
            if (flag)
            {
                switch (count)
                {
                case 1:s.push(" Thousand"); break;
                case 2:s.push(" Million"); break;
                case 3:s.push(" Billion"); break;
                default:break;
                }
            }

            s.push(temp);
            if ((int)temp.length() && !a.empty())
            {
                s.push(",");
            }
            count++;

        }
        string res;
        while (!s.empty())
        {
            res += s.top();
            s.pop();
        }
        return res;
    }
};
发表于 2019-04-04 21:36:21 回复(0)
vector<string> nums={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
vector<string> tenth={"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> mtenth={"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
vector<string> fin={"Hundred","Thousand","Million"};

class ToString {
public:

    void core(vector<string>& temp,string t,int idx1,int idx2)
    {
        if(idx2==idx1+1)
        {
            temp.empty()?temp.push_back(nums[t[idx1]-'0']):temp.push_back(nums[t[idx1]-'0']+' ');           
            return;
        }
        for(int i=idx1;i<idx2;i++)
        {
            while(i<idx2&&t[i]=='0')
                i++;
            int tpp=t[i]-'0';
            if(i-idx1==0)
            {
                if(t[i+1]-'0'== 1)
                {   
                    temp.empty()?temp.push_back(tenth[tpp]):temp.push_back(tenth[tpp]+' ');
                    i++;
                }
                else
                     temp.empty()?temp.push_back(nums[tpp]):temp.push_back(nums[tpp]+' ');
            }
            else if(i-idx1==1)           
                temp.empty()?temp.push_back(mtenth[tpp-2]):temp.push_back(mtenth[tpp-2]+' ');


            else if (i-idx1 == 2)
            {
                temp.empty()?temp.push_back(fin[0]):temp.push_back(fin[0]+' ');               
                temp.push_back(nums[tpp]+' ');
            }
        }
    }
    string merge(vector<string>& tp)
    {
        string out="";
        for(int i=tp.size()-1;i>=0;i--)
        {
            out+=tp[i];
        }
        return out;
    }
    string toString(int x) {
        // write code here
        string t="";
        while(x)
        {
            t+=(x%10)+'0';
            x/=10;
        }
        int l=t.length();
        vector<string> temp;

        core(temp,t,0,min(l,3));
        if(l>3)
        {
             temp.empty()?temp.push_back(fin[1]):temp.push_back(fin[1]+',');
            if(l<7)      
                core(temp,t,3,l);        
            else
            {
                int sz= temp.size();
                core(temp, t, 3, 6);
                if (temp.size()==sz)   
                    temp.pop_back();
                temp.empty()?temp.push_back(fin[2]):temp.push_back(fin[2]+',');                 
                core(temp, t, 6, l);
            }
        }

        return merge(temp);
    }
};
发表于 2018-07-02 11:27:44 回复(0)
class ToString {
public:
    vector<string> digits = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten" };
    vector<string> teens = {"", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
    vector<string> tens = {"","","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    vector<string> bigs = { "Hundred", "Thousand", "Million","Billion"};
        string fayin(int x)
        {
            string res;
            if(x < 0)
                return res;
            if(x <= 10 && x >0)
                res = digits[x];
            else if(x < 20&& x > 10)
                res = teens[x-10];
            else if(x < 100&& x >=20)
                res = tens[x/10]+ (x % 10 > 0 ? " " : "") +fayin(x%10);
            else if(x < 1000 && x >=100)
                res = fayin(x/100) + " " +bigs[0] +  (x % 100 > 0 ? " " : "") +fayin(x%100);
            else if(x < 1000000 && x >=1000)
                res = fayin(x/1000) + " " +bigs[1] +  (x % 1000 > 0 ? "," : "") + fayin(x%1000);
            else if(x < 1000000000 && x >= 1000000)
                res = fayin(x/1000000) + " " +bigs[2] + (x % 1000000 > 0 ? "," : "") + fayin(x%1000000);
            else if(x < 1000000000000 && x >= 1000000000)
                res = fayin(x/1000000000) + " " +bigs[3] + (x % 1000000000 > 0 ? "," : "") + fayin(x%1000000000);

            return res;

        }
    string toString(int x) {
        // write code here
        string res;
        if(x < 0)
            return res;
        else if(x == 0)
            res = "zero";
        else
        res = fayin(x);
        return res;
    }
};
发表于 2018-04-27 15:25:15 回复(0)
思路:判断数的范围,根据范围打印出相应的数值。有一点需要注意,就是逗号的选择,我是加了1个
          条件判断,x/N(N=million,billion,thousand,hundred,ten), 判断余数是否是0,进行选择性的
          打印","或""
class ToString {
public:
    string belowTen[10]={"","One","Two","Three","Four","Five","Six","Seven","Eight",
"Nine"};
    string belowTwenty[10]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen"};
    string belowHundred[10]={"","Ten","Twenty","Thirty","Forty","Fifty","Sixty",
"Seventy","Eighty","Ninety"};
    string toString(int x) {
        return fun(x);
    }
    string fun(int x)
        {
        string res="";
        string t="";
        if(x<=0)return "";
        else if(x<10)
            res=belowTen[x];
        else if(x<20)
            res=belowTwenty[x-10];
        else if(x<100)
            res=belowHundred[x/10]+(t=(x%10)>0?" ":"")+belowTen[x%10];
        else if(x<1000)
            res=fun(x/100)+" Hundred"+(t=(x%100)>0?" ":"")+fun(x%100);
        else if(x<1000000)
            res=fun(x/1000)+" Thousand"+(t=(x%1000)>0?",":"")+fun(x%1000);
        else if(x<1000000000)
            res=fun(x/1000000)+" Million"+(t=(x%1000000)>0?",":"")+fun(x%1000000);
        else 
            res=fun(x/1000000000)+" Billion"+(t=(x%1000000000)>0?",":"")+fun(x%1000000000);
        return res;
    }
};

编辑于 2017-10-02 18:43:14 回复(0)
//自己写到一半感觉不好,就参考了下赞最多的答主的方法
const vector<string> belowTen{ "", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine" };
const vector<string>  belowTwenty{ "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
const vector<string>  belowHundred{ "", "Ten", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
class ToString {
public:
    string toString(int x) {
        // write code here
        if (x == 0) return "Zero";
        return transform(x);
    }
    string transform(int x){
        string re = "";
        if (0 == x)
            return re;
        if (x < 10)
            re = belowTen[x];
        else if (x < 20)
            re = belowTwenty[x - 10];
        else if (x < 100)
            re = belowHundred[x / 10] + (x % 10 == 0 ? "" : " " + transform(x % 10));
        else if (x < 1000)
            re = transform(x / 100) + " Hundred" + (x % 100 == 0 ? "" : " " + transform(x % 100));
        else if (x < 1000000)
            re = transform(x / 1000) + " Thousand" + (x % 1000 == 0 ? "" : "," + transform(x % 1000));
        else if (x < 1000000000)
            re = transform(x / 1000000) + " Million" + (x % 1000000 == 0 ? "" : "," + transform(x % 1000000));
        else
            re = transform(x / 1000000000) + " Billion" + (x % 1000000000 > 0 ? "" : "," + transform(x % 1000000000));
        return re;
    }
};

发表于 2017-08-08 17:33:39 回复(1)
//直接用别人的代码了,不写了。。。
import java.util.*;

public class ToString {
 
    private String[] digits = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    private String[] teens = {"ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private String[] bits = {"", "Thousand", "Million", "Billion"};
 
    public String toString(int x) {
        String str = "";
        int index = 0;
        while (x > 0) {
            if (!str.equals("")) {
                str = dealCore(x % 1000, index) + "," + str;
            } else {
                str = dealCore(x % 1000, index);
            }
            x /= 1000;
            index++;
        }
        return str.trim();
    }
 
    private String dealCore(int n, int index) {
        String str = "";
        if (n / 100 > 0) {
            str = digits[n / 100] + " Hundred ";
            n %= 100;
        }
        if (n / 10 > 0) {
            if (10 <= n && n < 20) {
                str = str + teens[n - 10] + " ";
            } else {
                str = str + tens[n / 10] + " ";
                n %= 10;
                if (n > 0) {
                    str = str + digits[n] + " ";
                }
            }
            n = 0;
        }
        if (n > 0) {
            str = str + digits[n] + " ";
        }
        if (!str.equals("")) {
            str += bits[index];
        }
        return str;
    }
}


发表于 2017-06-09 20:55:13 回复(0)
这题是真麻烦 //借鉴的#id:唯美小小婷#的思路
class ToString {
public:
    string toString(int x) {
        // write code here
        string ret, temp;
        int index = 0;
        int val = 0;
        while(x > 0)
        {
            val = x % 1000;
            temp.erase(temp.begin(),temp.end());
            if(Special[val / 100] != "")//用空字符串判断数字0
                temp += Special[val / 100] + " Hundred";
            if(val % 100 < 20)
            {
                if(!temp.empty())
                    temp += " ";
                temp += Special[val % 100];
            }
            else
            {
                if(!temp.empty())
                    temp += " ";
                temp += Ty[val % 100 / 10];
                if(Special[val % 10] != "")
                {
                    if(!temp.empty())
                        temp += " ";
                    temp += Special[val % 10];
                }
            }
            if(!temp.empty() && HEX[index] != "")
            {
                temp += " " + HEX[index];
                if(!ret.empty())
                    temp += ",";
            }
            ret = temp + ret;
            ++index;
            x /= 1000;  
        }
        return ret;
    }
private:
    const static vector<string> Special ;//静态变量存储不会产生额外开销
    const static vector<string> Ty ;
    const static vector<string> HEX ;
};
      //后面的空字符串是防止数组越界
    const vector<string> ToString::Special = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Forteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",""};
    const vector<string> ToString::Ty = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",""};
    const vector<string> ToString::HEX = {"", "Thousand", "Million", "Billion", "Trillion",""};

发表于 2016-10-16 23:21:06 回复(0)
import java.util.*;

public class ToString {

    private String[] digits = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
    private String[] teens = {"ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private String[] bits = {"", "Thousand", "Million", "Billion"};

    public String toString(int x) {
        String str = "";
        int index = 0;
        while (x > 0) {
            if (!str.equals("")) {
                str = dealCore(x % 1000, index) + "," + str;
            } else {
                str = dealCore(x % 1000, index);
            }
            x /= 1000;
            index++;
        }
        return str.trim();
    }

    private String dealCore(int n, int index) {
        String str = "";
        if (n / 100 > 0) {
            str = digits[n / 100] + " Hundred ";
            n %= 100;
        }
        if (n / 10 > 0) {
            if (10 <= n && n < 20) {
                str = str + teens[n - 10] + " ";
            } else {
                str = str + tens[n / 10] + " ";
                n %= 10;
                if (n > 0) {
                    str = str + digits[n] + " ";
                }
            }
            n = 0;
        }
        if (n > 0) {
            str = str + digits[n] + " ";
        }
        if (!str.equals("")) {
            str += bits[index];
        }
        return str;
    }
}

发表于 2016-09-06 13:11:04 回复(0)
class ToString {
int cal_len(int x, vector<int>& num) {
int len = 0;
while (x > 0) {
num.push_back(x % 10);
x /= 10;
len++;
}
return len;
};
string new_num_des(vector<int> num, int x, bool& flag) {
string out;
flag = true;
vector<int> num_new(3);
if (num.size() >= (3 + x)) {
for (int cnt = 0; cnt < 3; cnt++) {
num_new[cnt] = num[cnt + x];
}
}
else if (num.size() == (2 + x)) {
num_new[0] = num[x];
num_new[1] = num[x + 1];
num_new[2] = 0;
}
else {
num_new[0] = num[x];
num_new[1] = 0;
num_new[2] = 0;
}
if (num_new[2] != 0) {
out += (describe(num_new[2]) + " Hundred ");
}
out += describe(10 * num_new[1] + num_new[0]);
if ((num_new[0] + num_new[1] + num_new[2]) == 0)
flag = false;
return out;
};
string out_Mil(int x, vector<int> num) {
string out;
bool flag;
out = new_num_des(num, 6, flag);
if (flag)
return out + " Million";
else
return "";
};
string out_Tho(int x, vector<int> num) {
string out;
bool flag;
out = new_num_des(num, 3, flag);
if (flag)
return out + " Thousand";
else
return "";
};
string out_low(int x, vector<int> num) {
string out;
bool flag;
out = new_num_des(num, 0, flag);
return out;
};
bool cal_sum(vector<int> num, int x) {
if (num[x] + num[x+1] + num[x+2])
return true;
else return false;
}
string describe(int n) {
int h = n / 10;
int l = n % 10;
string hh, ll;
string output;
switch (h) {
case 9:hh = "Ninety"; break;
case 8: hh = "Eighty"; break;
case 7: hh = "Seventy"; break;
case 6: hh = "Sixty"; break;
case 5: hh = "Fifty"; break;
case 4: hh = "Forty"; break;
case 3: hh = "Thirty"; break;
case 2: hh = "Twenty"; break;
case 1:
if (l == 9)hh = "Nineteen";
else if (l == 8) hh = "Eighteen";
else if (l == 7) hh = "Seventeen";
else if (l == 6) hh = "Sixteen";
else if (l == 5) hh = "Fifteen";
else if (l == 4) hh = "Forteen";
else if (l == 3) hh = "Thirteen";
else if (l == 2) hh = "Twelve";
else if (l == 1) hh = "Eleven";
else if (l == 0) hh = "Ten";
else hh = "";
break;
case 0: hh = ""; break;
default: break;
}
switch (l) {
case 9: ll = "Nine"; break;
case 8: ll = "Eight"; break;
case 7: ll = "Seven"; break;
case 6: ll = "Six"; break;
case 5: ll = "Five"; break;
case 4: ll = "Four"; break;
case 3: ll = "Three"; break;
case 2: ll = "Two"; break;
case 1: ll = "One"; break;
default: ll = ""; break;
}
if (h == 0) {
output = ll;
}
else if (h == 1) {
output = hh;
}
else if (l != 0){
output = hh + " " + ll;
}
        else 
            output = hh;
return output;
};
public:
string toString(int x) {
// write code here
        if (x < 0) return "";
if (x == 0)
return "Zero";
vector<int> num;
int size;
string final_string;
size = cal_len(x, num);
if (size > 6) {
final_string = out_Mil(x, num);
if (cal_sum(num, 3) == true)
final_string = final_string + "," + out_Tho(x, num);
if (cal_sum(num, 0) == true)
final_string = final_string + "," + out_low(x, num);
}
else if (size > 3) {
final_string = out_Tho(x, num);
if (cal_sum(num, 0) == true)
final_string = final_string + "," + out_low(x, num);
}
else {
final_string = out_low(x, num);
}
return final_string;
}
};
//这里用了switch,感觉应该用string数组更简洁好看一点。。。

发表于 2016-09-03 01:14:53 回复(0)

问题信息

难度:
25条回答 10832浏览

热门推荐

通过挑战的用户

查看代码