Efficiently Extract Integers into Arrays: A Concise Guide
Question:
Given an integer i, is there an efficient way to convert it into an array containing its individual numbers? For example, convert i = 987654321 to [9, 8, 7, 6, 5, 4, 3, 2, 1] without intermediate operations like ToString() and character iteration?
Answer:
Recursive solution using stack:
<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>
Another solution using a for loop:
<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-based method:
<code class="language-c#">private static int[] NumbersIn(int value) { // 处理 value 为 0 或负数的特殊情况 if (value == 0) { return new int[] { 0 }; } value = Math.Abs(value); // 确定数字位数 var digits = 1 + (int)Math.Log10(value); // 预分配数组 var buffer = new int[digits]; // 迭代并填充数组 for (var counter = 0; counter < digits; counter++) { buffer[digits - 1 - counter] = value % 10; value /= 10; } return buffer; }</code>
These solutions provide efficient and concise ways to extract numbers from integers, allowing seamless conversion to arrays of individual numbers.
The above is the detailed content of How to Efficiently Extract Digits from an Integer into an Array?. For more information, please follow other related articles on the PHP Chinese website!