puede utilizar logartihms para calcular la longitud de la int:
public static int IntLength(int i) {
if (i <= 0) throw new ArgumentOutOfRangeException();
return (int)Math.Floor(Math.Log10(i)) + 1;
}
se supera la prueba:
[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));
}
una la prueba rápida ha demostrado que el método de registro es 4 veces más rápido que el método de longitud int.ToString().
el método mostrado por GVS inferiores (con declaraciones if-) es otro 6 veces más rápido que el método de registro (!):
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();
}
aquí son los tiempos exactos de los números de 1 a 10 millones:
IntLengthToString: 4205ms
IntLengthLog10: 1122ms
IntLengthIf: 201ms
Siempre mantenga el microsegundos libres que están tratando de ganar contra el tiempo de lectura cara de la pobre diablo (usted mismo, supongo) que tiene que leer y depurar ese código más tarde. – reinierpost
@reinierpost no es una micro-optimización si dicho método se ejecuta, como, mil millones de veces en un ciclo llamado por miles de subprocesos diferentes. –
¿Duplicado de este? http://stackoverflow.com/questions/679602/fastest-way-to-calculate-the-decimal-length-of-an-integer-net –