整数到整数数组 C#

发布于 2024-10-10 16:03:27 字数 360 浏览 6 评论 0原文

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

兮子 2024-10-17 16:03:28

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

如果它适用于负数,您可以执行 n = Math.Abs​​(n) 但我认为这没有意义。

此外,如果它应该具有更高的性能,我可以通过进行类似二分搜索的 if 语句组合来确定位数来创建最终数组。

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

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

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

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

Update 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;
}
一绘本一梦想 2024-10-17 16:03:28
int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x);

但如果你想将其转换为 1,2,3,4,5:

int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x - 48);
int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x);

but if you want to convert it to 1,2,3,4,5:

int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x - 48);
世界和平 2024-10-17 16:03:28

我会这样做:

var result = new List<int>();
while (num != 0) {
    result.Insert(0, num % 10);
    num = num / 10;
}
return result.ToArray();

性能稍差但可能更优雅的是:

return num.ToString().Select(c => Convert.ToInt32(c.ToString())).ToArray();

请注意,这些都返回 1,2,3,4,5,6 而不是 49,50,51,52,53,54 (即字节字符 '1'、'2'、'3'、'4'、'5'、'6' 的代码)如您的代码所示。我认为这就是真正的意图?

I'd do it like this:

var result = new List<int>();
while (num != 0) {
    result.Insert(0, num % 10);
    num = num / 10;
}
return result.ToArray();

Slightly less performant but possibly more elegant is:

return num.ToString().Select(c => Convert.ToInt32(c.ToString())).ToArray();

Note that these both return 1,2,3,4,5,6 rather than 49,50,51,52,53,54 (i.e. the byte codes for the characters '1','2','3','4','5','6') as your code does. I assume this is the actual intent?

泪意 2024-10-17 16:03:28

使用从 int 到 string 的转换可能不是那么快。我将使用以下内容,

public static int[] ToDigitArray(int i)
{
    List<int> result = new List<int>();
    while (i != 0)
    {
        result.Add(i % 10);
        i /= 10;
    }
    return result.Reverse().ToArray();
}

但我必须注意,这仅适用于严格的正整数。

编辑:

我想出了一个替代方案。如果性能确实是一个问题,这可能会更快,尽管您只能通过亲自检查您的具体用法和应用程序来确定。

public static int[] ToDigitArray(int n)
{
    int[] result = new int[GetDigitArrayLength(n)];
    for (int i = 0; i < result.Length; i++)
    {
        result[result.Length - i - 1] = n % 10;
        n /= 10;
    }
    return result;
}
private static int GetDigitArrayLength(int n)
{
    if (n == 0)
        return 1;
    return 1 + (int)Math.Log10(n);
}

当 n 为非负数时,此方法有效。

Using conversion from int to string and back probably isn't that fast. I would use the following

public static int[] ToDigitArray(int i)
{
    List<int> result = new List<int>();
    while (i != 0)
    {
        result.Add(i % 10);
        i /= 10;
    }
    return result.Reverse().ToArray();
}

I do have to note that this only works for strictly positive integers.

EDIT:

I came up with an alternative. If performance really is an issue, this will probably be faster, although you can only be sure by checking it yourself for your specific usage and application.

public static int[] ToDigitArray(int n)
{
    int[] result = new int[GetDigitArrayLength(n)];
    for (int i = 0; i < result.Length; i++)
    {
        result[result.Length - i - 1] = n % 10;
        n /= 10;
    }
    return result;
}
private static int GetDigitArrayLength(int n)
{
    if (n == 0)
        return 1;
    return 1 + (int)Math.Log10(n);
}

This works when n is nonnegative.

你好,陌生人 2024-10-17 16:03:28

感谢 ASCII 字符表。使用上面的 LINQ 的简单答案会产生答案 + 48。

之一

int[] result = youtInt.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();

int[] result = youtInt.ToString().Select(o => int.Parse(o.ToString())).ToArray();

可以使用

Thanks to ASCII character table. The simple answer using LINQ above yields answer + 48.

Either

int[] result = youtInt.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();

or

int[] result = youtInt.ToString().Select(o => int.Parse(o.ToString())).ToArray();

can be used

痞味浪人 2024-10-17 16:03:28

您可以做到这一点,而无需将其转换为字符串并返回:

public static int[] intToArray(int num) {
  List<int> numbers = new List<int>();
  do {
    numbers.Insert(0, num % 10);
    num /= 10;
  } while (num > 0);
  return numbers.ToArray();
}

当然,它仅适用于正值,但您的原始代码也有该限制。

You can do that without converting it to a string and back:

public static int[] intToArray(int num) {
  List<int> numbers = new List<int>();
  do {
    numbers.Insert(0, num % 10);
    num /= 10;
  } while (num > 0);
  return numbers.ToArray();
}

It only works for positive values, of course, but your original code also have that limitation.

箹锭⒈辈孓 2024-10-17 16:03:28

我会按以下方式转换它

if (num == 0)  return new int[1] { 0 };           
var digits = new List<int>();
while (num > 0)
{
   digits.Add(num % 10);
   num /= 10;
}
 var arr = digits.ToArray().Reverse().ToArray();

I would convert it in the below manner

if (num == 0)  return new int[1] { 0 };           
var digits = new List<int>();
while (num > 0)
{
   digits.Add(num % 10);
   num /= 10;
}
 var arr = digits.ToArray().Reverse().ToArray();

熟人话多 2024-10-17 16:03:28
string DecimalToBase(int iDec, int numbase)
        {
            string strBin = "";
            int[] result = new int[32];
            int MaxBit = 32;
            for(; iDec > 0; iDec/=numbase)
            {
                int rem = iDec % numbase;
                    result[--MaxBit] = rem;
            } 
            for (int i=0;i<result.Length;i++)
                if ((int)result.GetValue(i) >= base10)
                    strBin += cHexa[(int)result.GetValue(i)%base10];
                else
                    strBin += result.GetValue(i);
            strBin = strBin.TrimStart(new char[] {'0'});
            return strBin;
        }
        int BaseToDecimal(string sBase, int numbase)
        {
            int dec = 0;
            int b;
            int iProduct=1;
            string sHexa = "";
            if (numbase > base10)
                for (int i=0;i<cHexa.Length;i++)
                    sHexa += cHexa.GetValue(i).ToString();
            for(int i=sBase.Length-1; i>=0; i--,iProduct *= numbase)
            {
                string sValue = sBase[i].ToString();
                if (sValue.IndexOfAny(cHexa) >=0)
                    b=iHexaNumeric[sHexa.IndexOf(sBase[i])];
                else 
                    b= (int) sBase[i] - asciiDiff;
                dec += (b * iProduct);
            } 
            return dec; 
        }
string DecimalToBase(int iDec, int numbase)
        {
            string strBin = "";
            int[] result = new int[32];
            int MaxBit = 32;
            for(; iDec > 0; iDec/=numbase)
            {
                int rem = iDec % numbase;
                    result[--MaxBit] = rem;
            } 
            for (int i=0;i<result.Length;i++)
                if ((int)result.GetValue(i) >= base10)
                    strBin += cHexa[(int)result.GetValue(i)%base10];
                else
                    strBin += result.GetValue(i);
            strBin = strBin.TrimStart(new char[] {'0'});
            return strBin;
        }
        int BaseToDecimal(string sBase, int numbase)
        {
            int dec = 0;
            int b;
            int iProduct=1;
            string sHexa = "";
            if (numbase > base10)
                for (int i=0;i<cHexa.Length;i++)
                    sHexa += cHexa.GetValue(i).ToString();
            for(int i=sBase.Length-1; i>=0; i--,iProduct *= numbase)
            {
                string sValue = sBase[i].ToString();
                if (sValue.IndexOfAny(cHexa) >=0)
                    b=iHexaNumeric[sHexa.IndexOf(sBase[i])];
                else 
                    b= (int) sBase[i] - asciiDiff;
                dec += (b * iProduct);
            } 
            return dec; 
        }
冷︶言冷语的世界 2024-10-17 16:03:28

我有类似的要求..我借鉴了许多好主意,并添加了一些缺失的部分..许多人没有处理零或负值。这就是我想到的:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            _n /= 10;
        }
        return digits;
    }

我认为这非常干净..尽管如此,我们确实在每次迭代中进行条件检查和一些无关的计算..虽然我认为在这种情况下它们是名义上的,但你可以这样进一步优化:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            //digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            digits[(length - i) - 1] = _n % 10;
            _n /= 10;
        }
        if (n < 0)
            digits[0] *= -1;
        return digits;
    }

i had similar requirement .. i took from many good ideas, and added a couple missing pieces .. where many folks weren’t handling zero or negative values. this is what i came up with:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            _n /= 10;
        }
        return digits;
    }

i think this is pretty clean .. although, it is true we're doing a conditional check and several extraneous calculations with each iteration .. while i think they’re nominal in this case, you could optimize a step further this way:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            //digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            digits[(length - i) - 1] = _n % 10;
            _n /= 10;
        }
        if (n < 0)
            digits[0] *= -1;
        return digits;
    }
夏花。依旧 2024-10-17 16:03:28

执行 MarkXA 的单行版本的一种稍微更简洁的方法:

int[] result = n.ToString().Select(c => (int)Char.GetNumericValue(c)).ToArray();

GetNumericValue 将 char 中的可见数字作为双精度值返回,因此如果您的字符串是“12345”,它将返回双精度值 1,2,3,4,5,其中每个都可以转换为 int。请注意,在 C# 中对 char 使用 Convert.ToInt32 返回 ASCII 代码,因此您将得到 49,50,51,52,53。可以理解,这可能会导致错误。

A slightly more concise way to do MarkXA's one-line version:

int[] result = n.ToString().Select(c => (int)Char.GetNumericValue(c)).ToArray();

GetNumericValue returns the visible number in your char as a double, so if your string is "12345", it will return the doubles 1,2,3,4,5, which can each be cast to an int. Note that using Convert.ToInt32 on a char in C# returns the ASCII code, so you would get 49,50,51,52,53. This can understandably lead to a mistake.

命比纸薄 2024-10-17 16:03:28

这是将整数转换为数组的一个很好的解决方案,即:
int a= 5478 转换为 int[]
例如,如果您有一个字符串并且想要将字符串转换为整数数组,则没有问题
字符串str=4561; //转换成
数组[0]=4;
数组[1]=5;
数组[2]=6;
array[3]=7;

注意:deider 中零 (0) 的数量等于输入的长度,并根据您的输入长度设置数组长度
现在检查编码:

         string str=4587;
            int value = Convert.ToInt32(str);
            int[] arr = new int[4];
            int devider = 10000;
            for (int i = 0; i < str.Length; i++)
            {
                int m = 0;
                devider /= 10;
                arr[i] = value / devider;
                m = value / devider;
                value -= (m * devider);
            }

Here is a Good Solution for Convert Your Integer into Array i.e:
int a= 5478 into int[]
There is no issue if You Have a String and You want to convert a String into integer Array for example
string str=4561; //Convert into
array[0]=4;
array[1]=5;
array[2]=6;
array[3]=7;

Note: The Number of zero (0) in devider are Equal to the Length of input and Set Your Array Length According to Your input length
Now Check the Coding:

         string str=4587;
            int value = Convert.ToInt32(str);
            int[] arr = new int[4];
            int devider = 10000;
            for (int i = 0; i < str.Length; i++)
            {
                int m = 0;
                devider /= 10;
                arr[i] = value / devider;
                m = value / devider;
                value -= (m * devider);
            }
情深缘浅 2024-10-17 16:03:28
 private static int[] ConvertIntToArray(int variable)
        {
            string converter = "" + variable;
            int[] convertedArray = new int[converter.Length];
            for (int i=0; i < convertedArray.Length;i++) //it can be also converter.Length
            {
                convertedArray[i] = int.Parse(converter.Substring(i, 1));
            }
            return convertedArray;
        }

我们通过 using 方法获取 int 。然后,立即将其转换为字符串(123456->“123456”)。我们有一个名为 converter 的字符串,并带有 int 值。我们的字符串有一个 string.Length,尤其是 int 的长度相同,因此,我们创建一个名为 convertedArrayarray我们有长度,即转换器(string)长度。然后,我们进入循环,使用string.Substring(i,1)将字符串一一转换为int,并赋值convertedArray[i] >。然后,返回 convertedArray。在 main 或任何可以轻松调用该方法的方法。

 private static int[] ConvertIntToArray(int variable)
        {
            string converter = "" + variable;
            int[] convertedArray = new int[converter.Length];
            for (int i=0; i < convertedArray.Length;i++) //it can be also converter.Length
            {
                convertedArray[i] = int.Parse(converter.Substring(i, 1));
            }
            return convertedArray;
        }

We get int via using method. Then, convert it to string immediately (123456->"123456"). We have a string called converter and carry to int value. Our string have a string.Length, especially same length of int so, we create an array called convertedArray that we have the length, that is converter(string) length. Then, we get in the loop where we are convert the string to int one by one via using string.Substring(i,1), and assign the value convertedArray[i]. Then, return the convertedArray.At the main or any method you can easily call the method.

浴红衣 2024-10-17 16:03:28
public static int[] intToArray(int num)
{
    num = Math.Abs(num);
    int length = num.ToString().Length;
    int[] arr = new int[length];
    do
    {
        arr[--length] = num % 10;
        num /= 10;
    } while (num != 0);

    return arr;
}

除以系统基数(在本例中为十进制)会删除最右边的数字,然后我们通过余数运算符得到该数字。我们不断重复,直到最终得到零。每次删除一个数字时,它都会从数组末尾开始向后存储在数组中,以避免需要在末尾反转数组。 Math.Abs​​() 函数用于处理负输入,并且数组被实例化为与输入长度相同的大小。

public static int[] intToArray(int num)
{
    num = Math.Abs(num);
    int length = num.ToString().Length;
    int[] arr = new int[length];
    do
    {
        arr[--length] = num % 10;
        num /= 10;
    } while (num != 0);

    return arr;
}

Dividing by system base (decimal in this case) removes the right most digit, and we get that digit by remainder operator. We keep repeating until we end up with a zero. Each time a digit is removed it will be stored in an array starting from the end of the array and backward to avoid the need of revering the array at the end. The Math.Abs() function is to handle the negative input, also the array is instantiated with the same size as input length.

十秒萌定你 2024-10-17 16:03:28

整数或长整型数组 C#
将其转换为 char 数组并减去 48。

 public static int[] IntToArray(int value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }

    public static int[] LongToIntArray(long value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }

Integer or Long to Integer Array C#
Convert it to char array and subtract 48.

 public static int[] IntToArray(int value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }

    public static int[] LongToIntArray(long value, int length)
    {
        char[] charArray = new char[length];
        charArray = value.ToString().ToCharArray();
        int[] intArray = new int[length];
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = charArray[i] - 48;
        }

        return intArray;
    }
如梦亦如幻 2024-10-17 16:03:27

使用 LINQ 的简单解决方案

int[] result = yourInt.ToString().Select(o=> Convert.ToInt32(o) - 48 ).ToArray()

A simple solution using LINQ

int[] result = yourInt.ToString().Select(o=> Convert.ToInt32(o) - 48 ).ToArray()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文