简体   繁体   English

将 Long 转换为整数数组

[英]Convert Long to Array of Integer Nums

How could I convert a long such as:我怎么能转换一个长的,例如:

123456789123456789

into:进入:

[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]

I ask because I need a way to iterate through a Long in C sharp, but Long apparently doesn't use [ ] for arrays, so I can't seem to access each number.我问是因为我需要一种方法来迭代 C 中的 Long,但 Long 显然没有将[ ]用于数组,所以我似乎无法访问每个数字。

This is pretty crude, but you could convert the long into a string and then break it up into single digits and convert them back to integers like this这很粗糙,但是您可以将 long 转换为字符串,然后将其分解为单个数字并将它们转换回整数,如下所示

var digits = 123456789123456789L.ToString().Select(d => int.Parse(d.ToString()));

To convert back from an array to a long, you can do要将数组转换回 long,您可以执行以下操作

var longFromDigits = digits.Aggregate(0L, (s, d) => s * 10 + d);

If you don't want to operate with string s you can just loop over digits with a help of modulo arithmetics:如果您不想使用string操作,您可以借助模运算来循环数字:

public static int[] Digits(long value) {
  if (value == 0)
    return new int[] { 0 };

  List<int> result = new List<int>();

  for (; value != 0; value /= 10)
    result.Add((int)Math.Abs(value % 10));

  result.Reverse();

  return result.ToArray();
}

then然后

int[] digits = Digits(123456789123456789L);

Edit: All you have to do is to Aggregate the digits to have the long back:编辑:您所要做的就是Aggregate digits以获得long背:

int[] digits = new [] { 1, 2, 3};

long result = digits.Aggregate(0L, (s, a) => s * 10 + a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM