int('1010',2)的时间复杂度是多少?

时间:2017-05-17 12:46:55

标签: python time-complexity

我只想知道python中int(<binary string>,2)的时间复杂度,将base-2二进制数字字符串转换为int

1 个答案:

答案 0 :(得分:4)

根据Python source code,从基数2或任何二次幂的基数转换,就字符数而言是O(N)。

/* *str points to the first digit in a string of base `base` digits.  base
 * is a power of 2 (2, 4, 8, 16, or 32).  *str is set to point to the first
 * non-digit (which may be *str!).  A normalized int is returned.
 * The point to this routine is that it takes time linear in the number of
 * string characters.

相比之下,似乎每个非基数幂都是(通常是?)O(N^2)

Binary bases can be converted in time linear in the number of digits, because
Python's representation base is binary.  Other bases (including decimal!) use
the simple quadratic-time algorithm below, complicated by some speed tricks.