Dot-Net

在.NET中查找整數的字元串長度

  • March 24, 2010

在 .NET 中,如果將整數表示為字元串,那麼在字元中查找整數長度的最佳方法是什麼?

例如

1 = 1 個字元

10 = 2 個字元

99 = 2 個字元

100 = 3 個字元

1000 = 4 個字元

顯而易見的答案是將 int 轉換為字元串並獲取其長度,但我希望盡可能獲得最佳性能,而無需創建新字元串的成本。

您可以使用對數來計算 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));
}

快速測試表明,log-method 比 int.ToString().Length 方法快 4 倍。

下面 GvS 顯示的方法(使用 if 語句)比 log 方法快 6 倍(!):

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 的確切時間:

IntLengthToString: 4205ms
IntLengthLog10: 1122ms
IntLengthIf: 201ms

引用自:https://stackoverflow.com/questions/2506476