整数到整数数组 C# [英] Integer to Integer Array C#

查看:52
本文介绍了整数到整数数组 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不将一个 int "123456" 的每个值拆分为一个 Int[] 并且我已经有了一个解决方案,但我不知道有没有更好的方法:我的解决方案是:

I had to split an int "123456" each value of it to an Int[] and i have already a Solution but i dont know is there any better way : My solution was :

public static int[] intToArray(int num){
    String holder = num.ToString();
    int[] numbers = new int[Holder.ToString().Length]; 
    for(int i=0;i<numbers.length;i++){
        numbers[i] = Convert.toInt32(holder.CharAt(i));
    }
    return numbers;
}

推荐答案

我相信这会比来回转换更好.与 JBSnorro 的答案相反,我在转换为数组后反转,因此避免了 IEnumerable,我认为这将有助于提高代码速度.此方法适用于非负数,因此 0 将返回 new int[1] { 0 }.

I believe this will be better than converting back and forth. As opposed to JBSnorro´s answer I reverse after converting to an array and therefore avoid IEnumerable´s which I think will contribute to a little bit faster code. This method work for non negative numbers, so 0 will return new int[1] { 0 }.

如果它适用于负数,你可以做一个 n = Math.Abs​​(n) 但我认为这没有意义.

If it should work for negative numbers, you could do a n = Math.Abs(n) but I don't think that makes sense.

此外,如果它的性能更高,我可以创建最终的数组,首先进行二进制搜索,例如结合 if 语句来确定位数.

Furthermore, if it should be more performant, I could create the final array to begin with by making a binary-search like combination of if-statements to determine the number of digits.

public static int[] digitArr(int n)
{
    if (n == 0) return new int[1] { 0 };

    var digits = new List<int>();

    for (; n != 0; n /= 10)
        digits.Add(n % 10);

    var arr = digits.ToArray();
    Array.Reverse(arr);
    return arr;
}

2018 年更新:

public static int numDigits(int n) {
    if (n < 0) {
        n = (n == Int32.MinValue) ? Int32.MaxValue : -n;
    }
    if (n < 10) return 1;
    if (n < 100) return 2;
    if (n < 1000) return 3;
    if (n < 10000) return 4;
    if (n < 100000) return 5;
    if (n < 1000000) return 6;
    if (n < 10000000) return 7;
    if (n < 100000000) return 8;
    if (n < 1000000000) return 9;
    return 10;
}

public static int[] digitArr2(int n)
{
    var result = new int[numDigits(n)];
    for (int i = result.Length - 1; i >= 0; i--) {
        result[i] = n % 10;
        n /= 10;
    }
    return result;
}

这篇关于整数到整数数组 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆