273. Integer to English Words
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
题目大意:
将一个数字转换成它的英文读法。
思路:
1.将数字以3位为一组,分组。
2.组合每组的字符串。
3.将每组字符串和自己的单位结合起来。
代码如下:
class Solution { public: string& trim(string &s) //C++ 去字符串两边的空格 { if (s.empty()) { return s; } s.erase(0,s.find_first_not_of(" ")); s.erase(s.find_last_not_of(" ") + 1); return s; } string numberToWords(int num) { if(num == 0) return "Zero"; string units_pre20[20] = {"","One","Two","Three","Four","Five", "Six","Seven","Eight","Nine","Ten", "Eleven","Twelve","Thirteen","Fourteen","Fifteen", "Sixteen","Seventeen","Eighteen","Nineteen"}; string units_10[10] = {"","","Twenty","Thirty","Forty","Fifty", "Sixty","Seventy","Eighty","Ninety"}; string units[4] = {"","Thousand","Million","Billion"}; vector<int > temp; int record = num; string result; while(record > 0)//3位分段 { temp.push_back(record % 1000); record /= 1000; } for(int i = 0; i < temp.size(); i++)//每段处理 { string tmpStr; int slices = temp[i]; int nHundreds = 0; int nTens = 0; int nUnits = 0; if(slices == 0) continue; if(slices >= 100) { nHundreds = slices / 100; tmpStr = tmpStr + units_pre20[nHundreds] + " Hundred"; slices = slices % 100; } if(slices >= 20) { tmpStr = tmpStr + " " + units_10[slices / 10] ; if(slices % 10 != 0) { tmpStr = tmpStr + " " + units_pre20[slices % 10]; } }else if(slices < 20 && slices > 0) { tmpStr = tmpStr + " " + units_pre20[slices]; } if(i != 0) { tmpStr = tmpStr + " " + units[i]; } result = tmpStr + " " + result; trim(result); } return result; } };
总结:
熟练度还是低,一个成熟的想法,需要半个多小时去实现。。。
呵呵,好吧,继续练习。
2016-08-19 17:38:50
时间: 2024-12-15 07:13:47