LeetCode 273. Integer to English Words

来源:互联网 发布:arm linux centos 编辑:程序博客网 时间:2024/05/29 19:24

题目链接: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十位是1            s.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;    }};
原创粉丝点击