Java中toCharArray()和toString()的运行时是什么?

时间:2012-10-26 00:29:48

标签: java algorithm data-structures arrays

这些的表现是什么?

BigInteger -> toString() // what is the runtime?

String -> toCharArray()  // what is the runtime?

感谢。

2 个答案:

答案 0 :(得分:3)

BigInteger到字符串的转换为O(N^2),其中N是结果中的位数,此时内部表示的基数不会划分目标基数;当目标库可被存储库整除时,转换需要O(N)

当内部表示为base-256时,请考虑转换为基数10。十分之一必须发生N次;每次,BigInteger表示的所有元素都会被修改。表示中的元素数量与打印输出中的位数成比例,因此整体转换需要O(N^2)

另一方面,在base-256内部表示中转换为big int的十六进制需要O(N),因为在这种情况下不需要除法。每个子元素可以与其余子元素隔离转换,子元素的数量与打印输出中的位数成比例。

String.toCharArray()而言,它是O(N),其中N是字符串中的字符数,因为每个字符都必须复制到输出中。

答案 1 :(得分:0)

toString()方法是使用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);
}

我认为本机方法可能使用内存下的memcpy是O(N),因此运行时O依赖于实际的jvm实现。您可以查看open jdk源以检查此本机方法的源。

相关问题