本文主要是介绍LeetCode 273. Integer to English Words,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:https://leetcode.com/problems/integer-to-english-words/description/
class Solution {
private:const vector<string> teens = { "Ten " , "Eleven " , "Twelve ", "Thirteen ","Fourteen ", "Fifteen ", "Sixteen ","Seventeen ", "Eighteen ", "Nineteen " };const vector<string> places[3] = {{ "", "One ", "Two ", "Three ", "Four ", "Five ","Six ", "Seven ", "Eight ", "Nine " },{ "", "Ten ", "Twenty ", "Thirty ", "Forty ", "Fifty ","Sixty ", "Seventy ", "Eighty ", "Ninety " },{ "", "One Hundred ", "Two Hundred ", "Three Hundred ","Four Hundred ", "Five Hundred ", "Six Hundred ","Seven Hundred ", "Eight Hundred ", "Nine Hundred " }};void add(string& s, int& num) {int x[3];for (int i = 0; i < 3; ++i) {x[i] = num % 10;num /= 10;}if (x[1] == 1) { //x十位是1s.insert(0, teens[x[0]]);s.insert(0, places[2][x[2]]);return;}for (int i = 0; i < 3; ++i)s.insert(0, places[i][x[i]]);}
public:string numberToWords(int num) {if (num == 0)return string("Zero");string res;int n = 0;while (true) {n++;if (num < pow(10, n))break;}string unit[4] = { "", "Thousand ", "Million ", "Billion " };for (int i = 0; i <= (n - 1) / 3; ++i) {int notZero = num - 1000 * (num / 1000);if (notZero)res.insert(0, unit[i]);add(res, num);}res.erase(res.size() - 1);return res;}
};
这篇关于LeetCode 273. Integer to English Words的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!