[英]Value was either too large or too small for a UInt64.'
My codes are like below. 我的代码如下。 I just want to try to convert number to binary and summarize binary numbers as if they are decimal ones, eg the desired outcome for
3
is 22
: 我只是想尝试将数字转换为二进制并汇总二进制数 ,就像它们是十进制数一样,例如
3
的期望结果是22
:
1 -> 1
2 -> 10
3 -> 11
-------
22 == 1 + 10 + 11
But number array is growing and the code blowing :) 但数字数组正在增长 ,代码正在吹 :)
static void Main(string[] args)
{
long deger = 1;
for (int i = 0; i < 1000000; i++)
{
deger *= (deger + 1);
int result = solve(deger);
Console.WriteLine(result);
}
}
public static int solve(long a)
{
ulong[] lastValue = new ulong[a];
for (int i = 1; i < a; i++)
{
var binary = Convert.ToString(i, 2);
lastValue[i] = Convert.ToUInt64(binary);// this part gives an error
}
var result = lastValue.Aggregate((t, c) => t + c);
return (int)result;
}
Look at UInt64.MaxValue
and UInt64.MinValue
. 查看
UInt64.MaxValue
和UInt64.MinValue
。
They defined as 18446744073709551615
and 0
corresponding. 他们定义为
18446744073709551615
和0
对应。
Well, UInt64
is not large enough ; 嗯,
UInt64
还不够大 ; you can try either BigInteger
or you may sum up string
s: 你可以尝试
BigInteger
或者你可以总结string
s:
private string MyBinarySum(string left, string right) {
var x = left
.PadLeft(Math.Max(left.Length, right.Length) + 1, '0')
.Reverse()
.Select(c => c - '0')
.ToArray();
var y = right
.PadLeft(Math.Max(left.Length, right.Length) + 1, '0')
.Reverse().Select(c => c - '0')
.ToArray();
StringBuilder sb = new StringBuilder(left.Length);
int shift = 0;
for (int i = 0; i < x.Length; ++i) {
int v = x[i] + y[i] + shift;
shift = v / 2;
v = v % 2;
sb.Append((char)('0' + v));
}
return String.Concat(sb.ToString().TrimEnd('0').Reverse());
}
Then, with a help of Linq 然后,在Linq的帮助下
var result = Enumerable
.Range(0, 1000000)
.Select(item => Convert.ToString(item, 2))
.Aggregate((sum, item) => MyBinarySum(sum, item));
Console.Write(result);
Outcome: 结果:
111010001101010010010101110011011100000
which is beyond UInt64.MaxValue == 18446744073709551615
这超出了
UInt64.MaxValue == 18446744073709551615
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.