在一些总结数字最快的方法 [英] Fastest way to sum digits in a number
问题描述
由于数量众多,例如 9223372036854775807
( Int64.MaxValue
),什么是总结数字的最快方法?
Given a large number, e.g. 9223372036854775807
(Int64.MaxValue
), what is the quickest way to sum the digits?
目前我ToStringing和重新分析每个字符到 INT
:
Currently I am ToStringing and reparsing each char into an int
:
num.ToString().Sum(c => int.Parse(new String(new char[] { c })));
这肯定是惊人,inefficent。有什么建议?
Which is surely horrifically inefficent. Any suggestions?
最后,你会怎么做与的BigInteger
?
感谢
推荐答案
好了,另一种选择是:
int sum = 0;
while (value != 0)
{
int remainder;
value = Math.DivRem(value, 10, out remainder);
sum += remainder;
}
的BigInteger
有 DivRem
的方法一样,所以你可以使用同样的方法。
BigInteger
has a DivRem
method as well, so you could use the same approach.
请注意,我已经看到 DivRem
不一样快,手动做相同的算术,所以如果你的真正的兴趣速度,你可能要考虑这一点。
Note that I've seen DivRem
not be as fast as doing the same arithmetic "manually", so if you're really interested in speed, you might want to consider that.
同时考虑与(比如说)的总和预先计算1000个元素查找表:
Also consider a lookup table with (say) 1000 elements precomputed with the sums:
int sum = 0;
while (value != 0)
{
int remainder;
value = Math.DivRem(value, 1000, out remainder);
sum += lookupTable[remainder];
}
这将意味着更少的反复,但每次迭代有一个附加的数组访问..
That would mean fewer iterations, but each iteration has an added array access...
这篇关于在一些总结数字最快的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!