这些的性能如何?
谢谢。
BigInteger -> toString() // what is the runtime?
String -> toCharArray() // what is the runtime?
谢谢。
BigInteger -> toString() // what is the runtime?
String -> toCharArray() // what is the runtime?
BigInteger
转换为字符串的时间复杂度为 O(N^2)
,其中 N
是结果中数字的位数,当内部表示的基数不能被目标基数整除时;当目标基数可被存储基数整除时,转换需要 O(N)
的时间复杂度。N
次除以 10 的运算;每次操作都会修改 BigInteger
表示中的所有元素。表示中的元素数量与输出中的位数成比例,因此总的转换时间复杂度为 O(N^2)
。O(N)
,因为此时不需要进行除法运算。每个子元素可以独立于其余元素进行转换,而子元素的数量与输出中的位数成比例。String.toCharArray()
,它的时间复杂度为 O(N)
,其中 N
是字符串中字符的数量,因为每个字符都必须被复制到输出中。toCharArray
是 O(N)
而不是 O(1)
吗?毕竟字符串已经以字符数组的形式存储了。 - arshajiitoCharArray
方法必须复制长度为N
的副本,导致时间复杂度为O(N)
。 - Sergey Kalinichenkoint
进行合成除法,并将乘积和余数向前传递。这使它在任何情况下都是 O(N)。 - Ted Hoppformat
方法。它有一个特殊情况是针对基数16的,时间复杂度为O(N)
,而其他情况(从第1502行开始)则看起来是O(N^2)
。 - Sergey KalinichenkotoString() 方法是使用 System.arrayCopy 实现的,这恰好是一个本地方法。
public char[] toCharArray() {
char result[] = new char[count];
getChars(0, count, result, 0);
return result;
}
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
// bounds checking
System.arraycopy(value, offset + srcBegin, dst, dstBegin,
srcEnd - srcBegin);
}