LeetCode - 整數轉換英文表示

題目鏈接:https://leetcode-cn.com/problems/integer-to-english-words/comments/

題目描述

將非負整數轉換爲其對應的英文表示。可以保證給定輸入小於 231 - 1 。

示例1:

輸入: 123
輸出: “One Hundred Twenty Three”

示例2:

輸入: 12345
輸出: “Twelve Thousand Three Hundred Forty Five”

示例3:

輸入: 1234567
輸出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”

示例4:

輸入: 1234567891
輸出: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”

我的思路

  • 這是一道“僞困難”算法題,LeetCode 難度判斷很迷,某些簡單題反而做得一頭包。
  • 這道題主要是要處理各種邊界情況比較多一些,另外存英文單詞用數組就行,我多此一舉用了map,敗筆。
  • 思路非常簡單,將整數從低位到高位三三分開,分別判斷就行。

代碼如下:

class Solution {
public:
    string three_numberToWords(int num){
        string en_num = "";
        unordered_map<int, string> en_num1 = {{0, ""}, {1, " One"}, {2, " Two"}, {3, " Three"}, {4, " Four"}, {5, " Five"}, {6, " Six"}, {7, " Seven"}, {8, " Eight"}, {9, " Nine"}, {10, " Ten"}, {11, " Eleven"}, {12, " Twelve"} ,{13, " Thirteen"} ,{14, " Fourteen"} ,{15, " Fifteen"} ,{16, " Sixteen"} ,{17, " Seventeen"} ,{18, " Eighteen"} ,{19, " Nineteen"}};
        unordered_map<int, string> en_num2 = {{0, ""}, {2, " Twenty"}, {3, " Thirty"}, {4, " Forty"}, {5, " Fifty"}, {6, " Sixty"}, {7, " Seventy"}, {8, " Eighty"}, {9, " Ninety"}};
        if(num < 20) return en_num1[num];
        if(num >= 20 && num < 100){
            return en_num2[num/10] + en_num1[num%10];
        }
        if(num >= 100 && num%100 >= 20){
            return en_num1[num/100] + " Hundred" + en_num2[num%100/10] + en_num1[num%100%10];
        }
        if(num >= 100 && num%100 < 20){
            return en_num1[num/100] + " Hundred" + en_num1[num%100];
        }
        return "";
    }
    string numberToWords(int num) {
        string res;
        if(num == 0) return "Zero";
        int billon = num / 1000000000;
        int milion = num % 1000000000 / 1000000;
        int thousand = num % 1000000000 % 1000000 / 1000;
        int simple = num % 1000000000 % 1000000 % 1000;
        if(billon != 0) res += three_numberToWords(billon) + " Billion";
        if(milion != 0) res += three_numberToWords(milion) + " Million";
        if(thousand != 0) res += three_numberToWords(thousand) + " Thousand";
        if(simple != 0) res += three_numberToWords(simple);
        while(res[res.size() - 1] == ' ') res.erase(res.end()-1);
        while(res[0] == ' ') res.erase(res.begin());
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章