Efficient integer to numeric array conversion method
Converting an integer to its array of single-digit numbers is a common task in programming. While the traditional approach using string conversion and iteration is simple, it is inefficient for large numbers. Here are some efficient conversion methods.
Recursive method
One way is to use recursion to break the integer into smaller parts. The following C# code demonstrates this approach:
<code class="language-c#">public Stack<int> NumbersIn(int value) { if (value == 0) return new Stack<int>(); var numbers = NumbersIn(value / 10); numbers.Push(value % 10); return numbers; } var numbers = NumbersIn(987654321).ToArray();</code>
Non-recursive stack method
A non-recursive version using the stack can also be implemented:
<code class="language-c#">public int[] NumbersIn(int value) { var numbers = new Stack<int>(); for (; value > 0; value /= 10) numbers.Push(value % 10); return numbers.ToArray(); }</code>
Direct array method
Another efficient method is to use direct array operations:
<code class="language-c#">private static int[] NumbersIn(int value) { if (value == 0) { return new[] { 0 }; // C# 12 集合表达式 } value = Math.Abs(value); var digits = 1 + (int)Math.Log10(value); var buffer = new int[digits]; for (var counter = 0; counter < digits; counter++) { buffer[counter] = value % 10; value /= 10; } Array.Reverse(buffer); return buffer; }</code>
These efficient methods provide a fast and memory-efficient way to convert integers into single-digit arrays, making them a valuable tool in a variety of programming tasks.
The above is the detailed content of How Can I Efficiently Convert an Integer into an Array of its Digits?. For more information, please follow other related articles on the PHP Chinese website!