高效的整数到文字的转换方法
问题:
如何有效地将整数转换为其文字形式?例如:
<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中文网其他相关文章!