Efficient integer to text conversion method
Question:
How to efficiently convert an integer to its literal form? For example:
<code>string 文字形式 = 整数转文字(21);</code>
Should output "Twenty One".
Is there a way to do this that doesn't rely on massive lookup tables?
Answer:
The following solution provides a practical approach:
<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>
This method avoids using large lookup tables. Instead, it breaks the integer into its different parts (thousands, hundreds, tens, ones) and converts each part separately. It supports numbers up to billions.
The above is the detailed content of How Can Integers Be Efficiently Converted to Their Written Forms Without Extensive Lookup Tables?. For more information, please follow other related articles on the PHP Chinese website!