Giliweed
Giliweed

Reputation: 5177

Access digits from integer value

I have an int variable (value1).

 Int value1 =95478;

I want to take each digit of value1 and insert them into an array (array1). Like this,

int[] array1 = { 9, 5, 4, 7, 8 };

No idea how this can be done. Any idea?

Upvotes: 0

Views: 118

Answers (3)

flindeberg
flindeberg

Reputation: 5007

The most optimal solution I could come up with:

public static class Extensions {
  public static int[] SplitByDigits(this int value) {
    value = Math.Abs(value); // undefined behaviour for negative values, lets just skip them
    // Initialize array of correct length
    var intArr = new int[(int)Math.Log10(value) + 1];
    for (int p = intArr.Length - 1; p >= 0; p--)
    {
      // Fill the array backwards with "last" digit
      intArr[p] = value % 10;
      // Go to "next" digit
      value /= 10;
    }
    return intArr;
  }
}

Is roughly double the speed of using a List<int> and reversing, roughly ten times faster and a tonne more memory efficient than using strings.

Just because you have a powerful computer you are not allowed to write bad code :)

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

int[] array1 =  95478.ToString()
                .Select(x => int.Parse(x.ToString()))
                .ToArray();

Upvotes: 3

faby
faby

Reputation: 7558

try this

    Int value1 =95478;
    List<int> listInts = new List<int>();
    while(value1 > 0)
    {
        listInts.Add(value1 % 10);
        value1 = value1 / 10;
    }
    listInts.Reverse();
    var result= listInts .ToArray();

this doesn't use strings

Upvotes: 3

Related Questions