Re: [閒聊] 每日leetcode

作者: oin1104 (是oin的說)   2024-08-07 13:06:08
※ 引述 《dont (dont)》 之銘言:
:  
: 273. Integer to English Words
:  
: ## 思路
:  
: 列出所有可能的英文字
: 1~19, 十位數, 百/千/百萬/十億
:  
: Input: num = 1234567
: Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty
: Seven"
:  
: 1,234,567 = 1 Million + 234 Thousand + 567
: 234 = 2 Hundred + 30 + 4
: 567 = 5 Hundred + 60 + 7
:  
: 把數字照10**9, 10**6, 10**3, 100順序切割做recursion轉換成英文
:  
: ## Code
思路:
因為jiwp很有錢
所以把錢給他處理
然後照題目硬做
這題真的好機掰
class Solution {
public:
unordered_map<int,string> save;
string jiwp(string n)
{
int now = stoi(n);
string res ;
if(save[now/100] != "Zero")
{
res+=save[(now/100)];
res+=" Hundred";
}
if(now%100>0)
{
if(!res.empty())res+=" ";
if(now%100 <20)
{
res+=save[now%100];
}
else
{
res += save[(now % 100) - (now % 10)];
if (now % 10 != 0)
{
res += " ";
res += save[now % 10];
}
}
}
return res;
}
string numberToWords(int num)
{
string nums = to_string(num);
if (num == 0) return "Zero";
save = {
{0, "Zero"}, {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"}, {20, "Twenty"}, {30, "Thirty"},
{40, "Forty"}, {50, "Fifty"}, {60, "Sixty"}, {70, "Seventy"},
{80, "Eighty"}, {90, "Ninety"}
};
int len = nums.size();
string res ;
if (len > 9)
{
res += jiwp(nums.substr(0, len - 9));
res += " Billion";
nums = nums.substr(len - 9);
len = nums.size();
}
if (len > 6)
{
if (!res.empty()&&res[res.size()-1] != ' ') res += " ";
res += jiwp(nums.substr(0, len - 6));
if(jiwp(nums.substr(0, len - 6)) != "" )res += " Million";
nums = nums.substr(len - 6);
len = nums.size();
}
if (len > 3)
{
if (!res.empty()&&res[res.size()-1] != ' ') res += " ";
res += jiwp(nums.substr(0, len - 3));
if(jiwp(nums.substr(0, len - 3)) != "" ) res += " Thousand";
nums = nums.substr(len - 3);
len = nums.size();
}
if (len > 0)
{
if (!res.empty()&&res[res.size()-1] != ' ') res += " ";
res += jiwp(nums.substr(0, len));
}
while(res[res.size()-1] == ' ')res.pop_back();
return res;
}
};
作者: mrsonic (typeB)   2023-08-07 13:06:00
你有什麼用
作者: SydLrio (狂嵐嘴砲)   2024-08-07 13:12:00
你有什麼用
作者: amsmsk (449)   2024-08-07 13:14:00
你有甚麼用

Links booklink

Contact Us: admin [ a t ] ucptt.com