高效率的整數到文字的轉換方法
問題:
如何有效地將整數轉換為其文字形式?例如:
<code>string 文字形式 = 整数转文字(21);</code>
應該輸出 "Twenty One"。
是否存在一種方法可以不依賴大量的查找表?
答案:
以下解決方案提供了一個實用方法:
<code class="language-c#">public static class HumanFriendlyInteger { static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" }; private static string FriendlyInteger(int n, string leftDigits, int thousands) { if (n == 0) { return leftDigits; } string friendlyInt = leftDigits; if (friendlyInt.Length > 0) { friendlyInt += " "; } if (n < 100) { if (n < 20) { friendlyInt += teens[n - 10]; } else { friendlyInt += tens[(n / 10) - 2]; if (n % 10 > 0) { friendlyInt += " " + ones[n % 10]; } } } else { friendlyInt += ones[n / 100] + " Hundred"; if (n % 100 > 0) { friendlyInt += " " + FriendlyInteger(n % 100, "", 0); } } return friendlyInt + thousandsGroups[thousands]; } public static string IntegerToWritten(int n) { if (n == 0) return "Zero"; if (n < 0) return "Minus " + IntegerToWritten(-n); string result = ""; int thousands = 0; while (n > 0) { result = FriendlyInteger(n % 1000, result, thousands) + result; n /= 1000; thousands++; } return result.Trim(); } }</code>
此方法避免了使用大型查找表。相反,它將整數分解成不同的部分(千位、百位、十位、個位),並分別轉換每一部分。它支援高達數十億的數字。
以上是在沒有大量查找表的情況下,如何將整數有效地轉換為其書面形式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!