Home > Backend Development > C++ > How Can I Efficiently Convert an Integer into an Array of its Digits?

How Can I Efficiently Convert an Integer into an Array of its Digits?

Barbara Streisand
Release: 2025-01-12 16:10:42
Original
238 people have browsed it

How Can I Efficiently Convert an Integer into an Array of its Digits?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template