Re: [閒聊] 每日leetcode

看板Marginalman作者 (xXx_5354M3_31M0_xXx)時間1年前 (2024/08/07 10:03), 編輯推噓2(202)
留言4則, 4人參與, 1年前最新討論串656/1550 (看更多)
273. Integer to English Words 思路:感覺就是 edge case 很多的題目,使用分進合擊的方式每百位數 0~999 進行處理 但是一堆空格會導致需要一堆條件判斷 跑起來速度大家都差不多,但是記憶體用量意外得少 https://i.imgur.com/BJiQQDh.png
class Solution { public: string numberToWords(int num) { string result = ""; int decimalPostFix = 0; do { string hundredsString = hundredsToString(num % 1000, decimalPostFix); if (hundredsString != "") { if (result == "") { result = hundredsString; } else { result = hundredsString + " " + result; } } num /= 1000; decimalPostFix++; } while (num != 0); if (result == "") { return "Zero"; } return result; } private: const string HUNDRED = "Hundred"; const array<string, 4> decimalPointString = { "", " Thousand", " Million", " Billion", }; const array<string, 20> zeroToNineteen = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", }; const array<string, 10> tenString = { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", }; string hundredsToString(int hundreds, int decimalPostFixIndex) { if (hundreds == 0) { return ""; } string result; int hundred = hundreds / 100; string hundredString = getHundredString(hundred); int tens = hundreds % 100; if (hundredString == "") { return getTensString(tens) + decimalPointString[decimalPostFixIndex]; } else { string tensString = getTensString(tens); if (tensString == "") { return hundredString + decimalPointString[decimalPostFixIndex]; } return hundredString + " " + tensString + decimalPointString[decimalPostFixIndex]; } return result; } string getHundredString(int hundred) { if (hundred == 0) { return ""; } return zeroToNineteen[hundred] + " " + HUNDRED; } string getTensString(int tens) { if (tens == 0) { return ""; } if (1 <= tens && tens <= 19) { return zeroToNineteen[tens]; } int ten = tens / 10; int singleDigit = tens % 10; string singleDigitString = getSingleDigitString(singleDigit); if (singleDigitString == "") { return tenString[ten]; } return tenString[ten] + " " + singleDigitString; } string getSingleDigitString(int singleDigit) { if (singleDigit == 0) { return ""; } return zeroToNineteen[singleDigit]; } }; -- https://i.imgur.com/pUTv8OI.jpg
https://i.imgur.com/lApcJec.jpg
https://i.imgur.com/kql2csq.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.228.71.204 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1722996200.A.A98.html

08/07 10:10, 1年前 , 1F
好苦喔這題
08/07 10:10, 1F

08/07 10:30, 1年前 , 2F
感覺leetcode一堆hard只是需求很複雜的題目
08/07 10:30, 2F

08/07 10:36, 1年前 , 3F
看一下題目完全不想寫==
08/07 10:36, 3F

08/07 15:34, 1年前 , 4F
大師
08/07 15:34, 4F
文章代碼(AID): #1cijNegO (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cijNegO (Marginalman)