Integer.parseInt(String i)和Integer.toString(int i)的运行时间是否都为O(n)?
wuzhijunxx 回答:Integer.parseInt()和Integer.toString()运行时
是的Integer.parseInt("1000")
和Integer.toString(1000)
都具有时间复杂度 O(N)
-
Integer.parseInt("1000")
的内部代码在while循环中逐字符读取字符串char和隐性字符串至十进制 -
Integer.toString(1000)
的内部代码读取整数并将每个数字转换为char并存储在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;
,
好吧,考虑一下,您只需添加+ ""
例如
String x = 555 + "";