[英]Integer.parseInt() and Integer.toString() runtime
Integer.parseInt(String i) 和 Integer.toString(int i) 的運行時間都是 O(n) 嗎?
是的,他們倆Integer.parseInt("1000")
和Integer.toString(1000)
的時間復雜度為O(N)
Integer.parseInt("1000")
的內部代碼在while循環中逐字符讀取字符串並轉換為十進制
Integer.toString(1000)
的內部代碼讀取整數並將每個數字轉換為字符並存儲在byte[] buf
然后從字節數組創建新字符串
這是
Integer.parseInt()
的代碼:int i = 0, len = s.length(); int limit = -Integer.MAX_VALUE; // some checks int multmin = limit / radix; int result = 0; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE int digit = Character.digit(s.charAt(i++), radix); if (digit < 0 || result < multmin) { throw NumberFormatException.forInputString(s, radix); } result *= radix; if (result < limit + digit) { throw NumberFormatException.forInputString(s, radix); } result -= digit; } return negative? result: -result;
好吧,考慮一下,您可以通過簡單地添加+ ""
來繞過 Integer.toString(int i) 的 O(n)
例如
String x = 555 + "";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.