簡體   English   中英

從整數值訪問數字

[英]Access digits from integer value

我有一個int變量( value1 )。

 Int value1 =95478;

我想獲取value1每個數字並將其插入到數組( array1 )中。 像這樣,

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

不知道如何做到這一點。 任何想法?

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

嘗試這個

    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();

這不使用字符串

我能想到的最佳解決方案:

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;
  }
}

大約是使用List<int>和反轉的速度的兩倍,大約比使用字符串快十倍,並且存儲效率高出一噸。

僅僅因為您有一台功能強大的計算機,就不能編寫錯誤的代碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM