我希望学习如何在C#中将int数组转换为int。但是我想要将int与数组中的值连接起来。
例如:
例如:
int[] array = {5, 6, 2, 4};
将会被转换为一个等于5624的整数。
提前感谢任何帮助。
只需将每个数字乘以其在数组中的位数上的10次方。
int[] array = { 5, 6, 2, 4 };
int finalScore = 0;
for (int i = 0; i < array.Length; i++)
{
finalScore += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}
int output = array
.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1)))
.Sum();
int[] array = {5, 6, 2, 4};
int num;
if (Int32.TryParse(string.Join("", array), out num))
{
//success - handle the number
}
else
{
//failed - too many digits in the array
}
这里的技巧是将数组转换为数字字符串,然后将其解析为整数。
如果您只想连接整数数组,请使用以下代码:
String a;
int output;
int[] array = {5, 6, 2, 4};
foreach(int test in array)
{
a+=test.toString();
}
output=int.parse(a);
//where output gives you desire out put
这不是精确的代码。
int[] intArray = new int[] { 5, 4, 6, 1, 6, 8 };
int total = 0;
for (int i = 0; i < intArray.Length; i++)
{
int index = intArray.Length - i - 1;
total += ((int)Math.Pow(10, index)) * intArray[i];
}
4265
- 这不是期望的结果。 - Michał Powagaint result = 0;
int[] arr = { 1, 2, 3, 4};
int multipicator = 1;
for (int i = arr.Length - 1; i >= 0; i--)
{
result += arr[i] * multipicator;
multipicator *= 10;
}
long result = array.Aggregate((result, x) => result * 10 + x);
array.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1))).Sum();
public int DoConvert(int[] arr)
{
int result = 0;
for (int i=0;i<arr.Length;i++)
result += arr[i] * Math.Pow(10, (arr.Length-1)-i);
return result;
}
var finalScore = int.Parse(array
.Select(x => x.ToString())
.Aggregate((prev, next) => prev + next));
int
的数,会发生什么? - Jon