问题描述
在.NET什么是找到字符的整数的长度最好的方式,如果它再presented作为一个字符串?
In .NET what is the best way to find the length of an integer in characters if it was represented as a string?
例如。
1 = 1个字符
10 = 2个字符
99 = 2个字符
100 = 3个字符
1000 = 4个字符
1 = 1 character
10 = 2 characters
99 = 2 characters
100 = 3 characters
1000 = 4 characters
答案显然是为int转换为字符串,并得到它的长度,但我想最佳的性能,而无需创建一个新的字符串的开销。
The obvious answer is to convert the int to a string and get its length but I want the best performance possible without the overhead of creating a new string.
推荐答案
您可以使用logartihms计算INT的长度:
you can use logartihms to calculate the length of the int:
public static int IntLength(int i) {
if (i <= 0) throw new ArgumentOutOfRangeException();
return (int)Math.Floor(Math.Log10(i)) + 1;
}
测试通过:
[Test]
public void TestIntLength() {
Assert.AreEqual(1, IntLength(1));
Assert.AreEqual(1, IntLength(9));
Assert.AreEqual(2, IntLength(10));
Assert.AreEqual(2, IntLength(99));
Assert.AreEqual(3, IntLength(100));
Assert.AreEqual(3, IntLength(999));
Assert.AreEqual(4, IntLength(1000));
Assert.AreEqual(10, IntLength(int.MaxValue));
}
快速测试已经表明,对数方法比int.ToString()。持续方法快4倍..
a quick test has shown that the log-method is 4 times faster than the int.ToString().Length method..
由GVS以下所示的方法(使用if语句)是另一个6倍以上日志方法快(!):
the method shown by GvS below (using if-statements) is another 6 times (!) faster than the log method:
public static int IntLengthIf(int i) {
if (i < 10) return 1;
if (i < 100) return 2;
if (i < 1000) return 3;
if (i < 10000) return 4;
if (i < 100000) return 5;
if (i < 1000000) return 6;
if (i < 10000000) return 7;
if (i < 100000000) return 8;
if (i < 1000000000) return 9;
throw new ArgumentOutOfRangeException();
}
下面是详细的时序为数字1至10000000:
here are the exact timings for the numbers 1 to 10000000:
IntLengthToString: 4205ms
IntLengthLog10: 1122ms
IntLengthIf: 201ms
这篇关于寻找在.NET中的整数的字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!