Integer.parseInt() 和 Integer.toString() 运行时
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
中,然后从字节数组创建新字符串
Here is the code of 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.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
中,然后从字节数组创建新字符串
Here is the code of
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;