Home > Backend Development > C++ > How to Efficiently Extract Digits from an Integer into an Array?

How to Efficiently Extract Digits from an Integer into an Array?

Patricia Arquette
Release: 2025-01-12 16:22:43
Original
870 people have browsed it

How to Efficiently Extract Digits from an Integer into an Array?

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

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

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

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!

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