Converting an integer to its literal representation is a common programming task. However, achieving efficiency without using large lookup tables can be challenging. This article explores one way to overcome this limitation.
The core of the solution is a class called HumanFriendlyInteger
. It contains a set of arrays to represent different face values (e.g. ones, tens, etc.), and a method called FriendlyInteger
that recursively builds the literal representation.
FriendlyInteger
method operates recursively to construct literal numbers. The process is as follows:
n
is 0, return the current leftDigits
(used to handle the leftmost digit). n
is less than 10, use the units array directly to retrieve the literal form. For values between 10 and 19, it uses an array of tens. n
is between 20 and 99, recursively convert n % 10
(the ones digit) and prepend it with the tens digit representation (e.g., "Thirty"). n % 100
(tens and ones digits) and prepends the hundreds digit representation in front of it. n % 1000
and appends the appropriate thousandth group representation (e.g., "Thousand", "Million"). If n % 1000
is 0, the recursion ends. IntegerToWritten
method is a wrapper function that handles the special case of negative numbers and 0, returning "Zero".
Consider the following usage examples:
<code class="language-csharp">using HumanFriendlyInteger; public class Program { public static void Main() { int number = 21; string writtenNumber = IntegerToWritten(number); Console.WriteLine($"{number} 的文字形式:{writtenNumber}"); } }</code>
This code will output:
<code>21 的文字形式:Twenty One</code>
This recursive approach provides an efficient way to convert integers to their literal form without relying on large lookup tables. By breaking the problem into smaller parts, this approach achieves the desired results with minimal overhead.
The above is the detailed content of How Can We Efficiently Convert Integers to Their Written Number Equivalents in C#?. For more information, please follow other related articles on the PHP Chinese website!